How can I return values from a recursive function?

I have my code which does a quick sort on a list of values:

def Quick_sort_random(random_list):
    r = random_list.copy()
    def inner(r):
        if len(r) < 2:
            return r
        p = random.randint(0, len(r) - 1)
        pivot = r[p]
        left = list(filter(lambda x: x <= pivot, r[:p] + r[p + 1:]))
        right = list(filter(lambda x: x > pivot, r[:p] + r[p + 1:]))
        return Quick_sort_random(left) + [pivot] + Quick_sort_random(right)
    a = inner(r)
    return random_list,a 

This throws the error:

TypeError: can only concatenate tuple (not "list") to tuple

I have the inner() function because I want to return both the original list and the sorted list. How can I fix this?

>Solution :

Your Quick_sort_random function returns a tuple but you only need the second item in it for the sorting. Change the last line in inner to:

return Quick_sort_random(left)[1] + [pivot] + Quick_sort_random(right)[1]

Leave a Reply