保存递归函数的多个值

时间:2019-01-15 05:15:34

标签: python recursion

我正在编写一个快速排序功能,并使用递归来“分而治之”。我正在尝试对函数调用自身的次数进行计数。但是,显然我在递归的概念上遇到了麻烦,因为我无法保存第二个值来保持计数。我曾尝试将input_stringloops的格式设置为tupledictionary,但我认为我对应该如何做有根本的误解。如何将2个值成功传递给我的递归函数?

def quickSort(input_string, loops):
    string_list = list(input_string)
    less = []
    equal = []
    greater = []

    loops = list(loops)
    loops.append(1)
    if len(string_list) > 1:
        split_val = string_list[0]
        for i in string_list:
            if i < split_val:
                less.append(i)
            elif i == split_val:
                equal.append(i)
            else:
                greater.append(i)
        out = (quickSort(less, loops) + equal + quickSort(greater, loops)), loops
        return out

    else:
        return string_list

我正在使用此处定义的快速排序功能:https://stackoverflow.com/a/18262384/5500488

1 个答案:

答案 0 :(得分:1)

您可以跟踪函数在每次递归调用中调用自身的次数,对其求和并加2(因为该函数在非终止条件下调用其自身两次),在终止条件下,输入的长度为1,则应返回0作为函数调用自身的次数:

def quickSort(input_string):
    string_list = list(input_string)
    less = []
    equal = []
    greater = []

    if len(string_list) > 1:
        split_val = string_list[0]
        for i in string_list:
            if i < split_val:
                less.append(i)
            elif i == split_val:
                equal.append(i)
            else:
                greater.append(i)
        sorted_less, count_less = quickSort(less)
        sorted_greater, count_greater = quickSort(greater)
        return sorted_less + equal + sorted_greater, count_less + count_greater + 2

    else:
        return string_list, 0

使quickSort('gehdcabf')返回:

(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 10)