pythonlistglobal-variables

I am getting a type error when trying to return count along with the sorted lost


count = 0
def merge(L1,L2):
    m = len(L1)
    n = len(L2)
    i = 0 
    j = 0 
    c = []
    k = 0
    
    while i<m and j<n:
        if L1[i]<=L2[j]:
            c.append(L1[i])
            i += 1
        else:
            c.append(L2[j])
            j += 1
    while i<m:
        c.append(L1[i])
        i += 1
    while j<n:
        c.append(L2[j])
        j += 1
    return c

def subordinates(L):
    length = len(L)
    global count 
    count = count + 1    
        
    if length <= 1:
        return L
    
    L1 = subordinates(L[:length//2])
    L2 = subordinates(L[length//2:])
    sorted_list = merge(L1,L2)

    
    return sorted_list

x = [10, 33, 45, 67, 92, 100, 5, 99, 105]
print(subordinates(x))

The above code sorts x correctly and returns the list.

However when I run: return (sorted_list,count) it does not let me return the count. It gives a type error:

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


Solution

  • This is happening because, when you modify the subordinates function to return a tuple (sorted_list, count), the recursive calls is returning tuples instead of lists. The merge function is expecting lists of int, but it's receiving tuples, thats why you are getting this TypeError.

    you just need to unpack the tuple when you call subordinates, so you can do something like this-

    count = 0
    
    def merge(L1, L2):
        m = len(L1)
        n = len(L2)
        i = 0
        j = 0
        c = []
        k = 0
    
        while i < m and j < n:
            if L1[i] <= L2[j]:
                c.append(L1[i])
                i += 1
            else:
                c.append(L2[j])
                j += 1
        while i < m:
            c.append(L1[i])
            i += 1
        while j < n:
            c.append(L2[j])
            j += 1
        return c
    
    
    def subordinates(L):
        length = len(L)
        global count
        count = count + 1
    
        if length <= 1:
            return L, count
    
        L1, _ = subordinates(L[: length // 2])
        L2, _ = subordinates(L[length // 2 :])
        sorted_list = merge(L1, L2)
    
        return sorted_list, count
    
    
    x = [10, 33, 45, 67, 92, 100, 5, 99, 105]
    print(subordinates(x))