简体   繁体   中英

Python Merge Sort TypeError at Runtime

I am writing a merge_sort program which is not running. It shows error

if  a[j] < b[k]:

TypeError: '<' not supported between instances of 'int' and 'list'

l=[int(n) for n in input().split()]

def merge_sort(l):
    if len(l)==1:
        return l
    else:
        a=l[:len(l)//2]
        b=l[len(l)//2:]
        print(a,b)
        a=merge_sort(a)
        b=merge_sort(b)
        j=0
        k=0

        for i in range(0,len(l)):
            if  a[j] < b[k]:
                l[i]=a[j]
                j+=1
                if j==len(a):
                    l=l.append(b[k:])
                    break
            else:
                l[i]=b[k]
                k+=1
                if k==len(b):
                    l=l.append(a[j:])
                    break
        # print(l)
        return l

print(merge_sort(l))

Here is the the error message.

Traceback (most recent call last):
  File "E:/STUFF/Python/Scripts/COURSERA/merge_sort.py", line 30, in <module>
    print(merge_sort(l))
  File "E:/STUFF/Python/Scripts/COURSERA/merge_sort.py", line 10, in merge_sort
    merge_sort(b)
  File "E:/STUFF/Python/Scripts/COURSERA/merge_sort.py", line 15, in merge_sort
    if  a[j] < b[k]:
TypeError: '<' not supported between instances of 'int' and 'list'

Process finished with exit code 1

Looks like you appending list of ints to the end of list of ints here:

 l=l.append(b[k:])

So if l = [1, 2, 3] and b[k:] = [4, 5], you'll getting

l.append(b[k:])
Out:
[1, 2, 3, [4, 5]]

Also list.append() returns None, and you don't need assign it to l. Try to use

l.extend(b[k:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM