如何计算递归函数?

时间:2017-07-14 04:25:58

标签: python-3.x

以下代码是Python中的快速排序。 如何计算算法中比较运行的次数?

虽然我首先指定count = 0,但由于递归,它会重置为0。

def QuickSort(lst):
    if len(lst) > 1:
        pivot_idx = len(lst) // 2
        smaller_nums, larger_nums = [], []

        for idx, num in enumerate(lst):
            if idx != pivot_idx:
                if num < lst[pivot_idx]:
                    smaller_nums.append(num)

                else:
                    larger_nums.append(num)

        QuickSort(smaller_nums)
        QuickSort(larger_nums)
        lst[:] = smaller_nums + [lst[pivot_idx]] + larger_nums

    return lst

3 个答案:

答案 0 :(得分:3)

  

编辑,我删除了这个答案,因为我认为这是不正确的,但我认为这毕竟是正确的

如建议的那样,如果函数是无状态的,我认为也会更好: 您可以返回lst和呼叫数量:

def QuickSort(lst, ncalls=0):
  ncalls += 1

  if len(lst) > 1:
    pivot_idx = len(lst) // 2
    smaller_nums, larger_nums = [], []

    for idx, num in enumerate(lst):
        if idx != pivot_idx:
            if num < lst[pivot_idx]:
                smaller_nums.append(num)

            else:
                larger_nums.append(num)
    lst1, ncalls = QuickSort(smaller_nums, ncalls)
    lst1, ncalls = QuickSort(larger_nums, ncalls)
    lst[:] = smaller_nums + [lst[pivot_idx]] + larger_nums



  return lst,ncalls


QuickSort([1,3,52,4,6,5])
=> [1, 3, 4, 5, 6, 52],7

答案 1 :(得分:1)

将其递归传递为参数:

def QuickSort(lst, count=0):
    if len(lst) > 1:
        pivot_idx = len(lst) // 2
        smaller_nums, larger_nums = [], []

        for idx, num in enumerate(lst):
            if idx != pivot_idx:
                if num < lst[pivot_idx]:
                    smaller_nums.append(num)

                else:
                    larger_nums.append(num)

        count = QuickSort(smaller_nums, count+1)[1]
        count = QuickSort(larger_nums, count+1)[1]
        lst[:] = smaller_nums + [lst[pivot_idx]] + larger_nums


    return (lst,count)

答案 2 :(得分:-2)

将count指定为全局变量并将其设置为零。也就是说,将count=0设置在函数定义之外,并在每次比较时递增它。