I am a high school student doing a simple merge sort algorithm, but I encountered below error message. Help is much appreciated!
File "main.py", line 22, in mergesort
if l_list[i] <= r_list[j]:
TypeError: ‘<=’ not supported between instances of ‘int’ and ‘list’
Here’s my code:
list = [1, 3, 5, 6, 2]
def mergesort(list):
n = len(list)
if n <= 1:
return
mid_cut = n // 2
l_list = list[:mid_cut]
r_list = list[mid_cut:]
mergesort(l_list)
mergesort(r_list)
i = 0
j = 0
list.clear()
while i < len(l_list) and j < len(r_list):
if l_list[i] <= r_list[j]:
list.append(l_list[i])
i += 1
else:
list.append(r_list[j])
j += 1
if i < len(l_list):
list.append(l_list[i:])
else:
list.append(r_list[j:])
mergesort(list)
I tried extracting items from two local lists and compare them, but one of the "item" turned into a list somehow.
>Solution :
In this code, you append slices to list.
if i < len(l_list):
list.append(l_list[i:])
else:
list.append(r_list[j:])
Use list.extend(…) instead:
if i < len(l_list):
list.extend(l_list[i:])
else:
list.extend(r_list[j:])