简体   繁体   中英

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?

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]

Just return the sorted list in inner function:

import random

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:]))
        unsorted_left, sorted_left = Quick_sort_random(left)
        unsorted_right, sorted_right = Quick_sort_random(right)
        return sorted_left + [pivot] + sorted_right
    a = inner(r)
    return random_list,a 

print(Quick_sort_random([4,5,1,5,2,3]))

Output:

([4, 5, 1, 5, 2, 3], [1, 2, 3, 4, 5, 5])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM