Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list[I] becomes a list instead of an item

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading