0

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
5
  • 1
    Careful, you are manipulating the global variable l in your loop. I doubt that's what you intended. Commented Aug 19, 2018 at 13:47
  • When asking about code that produces an Exception you should always include the complete Traceback in the question. Copy the Traceback and paste it in the question, then format it as code (select it and type ctrl-k) Commented Aug 19, 2018 at 13:51
  • When you do "merge_sort(a)" and "merge_sort(b)", you are not changing "a" and "b." Make sure to do a = merge_sort(a) and b = merge_sort(b). Commented Aug 19, 2018 at 13:53
  • @chrisaycock A separate copy is created every time the function is called. Then how can it cause a problem ? Commented Aug 19, 2018 at 14:02
  • A separate copy is not made. However, the name l in the function is local to the function, so it's a separate name to the l in the global scope. Commented Aug 19, 2018 at 14:06

1 Answer 1

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:])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.