Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading