我正在看這個代碼挑戰:
定義一個函式回圈,它接受三個函式
f1,f2,f3, 作為引數。cycle 將回傳另一個函式,該函式應該接受一個整數引數 n 并回傳另一個函式。最后的函式應該接受一個引數x并回圈應用f1,f2和f3tox,這取決于是什么n。下面是最終函式應該
x對 的幾個值執行的操作n:
n= 0,回傳x
n= 1,適用f1于x,或回傳f1(x)
n= 2, 應用f1到x那個f2結果,或者回傳f2(f1(x))
n= 3,應用f1到x,應用到f2應用的結果f1,然后應用f3到 應用的結果f2,或者f3(f2(f1(x)))
n= 4,再次開始回圈應用f1,然后f2,然后f3,然后f1再,或f1(f3(f2(f1(x))))等等。
以下是我的代碼,但該案例出現以下錯誤add_one_then_double:
RecursionError:超出最大遞回深度
有人可以幫我嗎?謝謝!
def cycle(f1, f2, f3):
"""
>>> def add1(x):
... return x 1
>>> def times2(x):
... return x * 2
>>> def add3(x):
... return x 3
>>> my_cycle = cycle(add1, times2, add3)
>>> identity = my_cycle(0)
>>> identity(5)
5
>>> add_one_then_double = my_cycle(2)
>>> add_one_then_double(1)
4
>>> do_all_functions = my_cycle(3)
>>> do_all_functions(2)
9
>>> do_more_than_a_cycle = my_cycle(4)
>>> do_more_than_a_cycle(2)
10
>>> do_two_cycles = my_cycle(6)
>>> do_two_cycles(1)
19
"""
def cycle_func(n):
i=1
result=lambda x:x
while i<n 1:
if i%3==1:
result=lambda x: f1(result(x))
elif i%3==2:
result=lambda x: f2(result(x))
else:
result=lambda x: f3(result(x))
i=i 1
return result
return cycle_func
uj5u.com熱心網友回復:
問題是這樣的陳述:
result=lambda x: f1(result(x))
當這個賦值被執行時,result將被賦予這個新的 lambda 函式。稍后執行時,result(x)將參考同一個函式,因此存在無限遞回。在這里,您打算參考 的先前值result,但如您所見,在此分配發生時該值已丟失。
解決方案是不在那里創建那些“小” lambda 函式,而是創建一個獲取 的值的內部函式,x然后通過這個邏輯來確定下一步要執行什么。
這是更正后的代碼:
def cycle(f1, f2, f3):
def cycle_func(n):
def inner(x):
i = 1
result = x
while i < n 1:
if i % 3 == 1:
result = f1(result)
elif i % 3 == 2:
result = f2(result)
else:
result = f3(result)
i = i 1
return result
return inner
return cycle_func
def add1(x):
return x 1
def times2(x):
return x * 2
def add3(x):
return x 3
my_cycle = cycle(add1, times2, add3)
identity = my_cycle(0)
print(identity(5)) # 5
add_one_then_double = my_cycle(2)
print(add_one_then_double(1)) # 4
do_all_functions = my_cycle(3)
print(do_all_functions(2)) # 9
do_more_than_a_cycle = my_cycle(4)
print(do_more_than_a_cycle(2)) # 10
do_two_cycles = my_cycle(6)
print(do_two_cycles(1)) # 19
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/416829.html
標籤:
