类似的递归函数有巨大的运行时差异。这是为什么?
我正在研究递归,我需要编写一个递归函数来计算给定列表中的最大整数。
首先我试过这个:
def find_max(L):
if len(L) == 1: return L[0]
mx = L[0]
return mx if mx > find_max(L[1:]) else find_max(L[1:])
然后我找到了另一种方法,它是:
def find_max2(L):
if len(L) == 1: return L[0]
rest = find_max(L[1:])
if rest > L[0]: return rest
else: return L[0]
我想检查差异,所以我导入了 Numpy 并创建了一个包含随机整数的列表
import numpy as np
np.random.seed()
nums = np.random.randint(10000,size=(25,1))
import time
#FIRST APPROACH
s = time.perf_counter_ns()
print(find_max(nums))
e = time.perf_counter_ns()
print("Elapsed time for the find_max:",e-s,"ns")
#SECOND APPROACH
s = time.perf_counter_ns()
print(find_max2(nums))
e = time.perf_counter_ns()
print("Elapsed time for the find_max2:",e-s,"ns")
我意识到第一个比第二个慢 2 倍。
D:CodesPython
? python recursion.py
[9726]
Elapsed time for the find_max: 735373900 ns
[9726]
Elapsed time for the find_max2: 362327100 ns
D:CodesPython
? python recursion.py
[9939]
Elapsed time for the find_max: 4889083400 ns
[9939]
Elapsed time for the find_max2: 2200926700 ns
D:CodesPython
? python recursion.py
[9913]
Elapsed time for the find_max: 5955406900 ns
[9913]
Elapsed time for the find_max2: 3069119000 ns
我试图弄清楚为什么会这样。然而我不能......如果有人能告诉我为什么会这样,我会很感激!
回答
这里发生了两件事:首先,您在第一个函数的最后一行中递归调用 find_max 两次 - 这意味着每次向下递归一个级别,活动调用的数量都会增加一倍。发生的第二件事是在函数 find_max2 中递归调用 find_max,而不是 find_max2。这个固定的运行find_max2应该给你多少更快的运行时:
def find_max2(L):
if len(L) == 1: return L[0]
rest = find_max2(L[1:])
if rest > L[0]: return rest
else: return L[0]