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

  • You're trying to return a tuple but you're not accounting for that when assigning to L1 and L2.

    You can remedy that as follows:

    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, 0
    
        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))
    

    Output:

    ([5, 10, 33, 45, 67, 92, 99, 100, 105], 17)
    

    Of course, there's no real need to return count as it's available globally