輸入
sum_possible(2017, [4, 2, 10]) # -> False
使用anywhich 導致RecursionError: maximum recursion depth exceeded
def sum_possible(amount, numbers, cache = None):
if cache is None:
cache = {}
if amount in cache:
return cache[amount]
if amount == 0:
return True
if amount < 0:
return False
cache[amount] = any(sum_possible(amount - number, numbers, cache) for number in numbers)
return cache[amount]
使用for解決方案的回圈
def sum_possible(amount, numbers, cache = None):
if cache is None:
cache = {}
if amount in cache:
return cache[amount]
if amount == 0:
return True
if amount < 0:
return False
for number in numbers:
if sum_possible(amount - number, numbers, cache):
cache[amount] = True
return True
cache[amount] = False
return False
uj5u.com熱心網友回復:
默認遞回限制為 1000 次呼叫。雖然它被稱為“遞回限制”,但它實際上是所有嵌套函式呼叫的最大深度——我們只是用遞回來描述它,因為沒有遞回很難達到極限——你需要數百個不同的函式相互呼叫. 超過遞回限制的最常見原因是“無限”遞回(例如,未能正確檢測基本情況)。
在帶有for回圈的版本中,允許 1000 個遞回級別。連同快取,這對于您的測驗用例來說已經足夠了。
在使用 的版本中any(),有效遞回限制減半,因為每個遞回呼叫都在對 的呼叫中any()。這還不夠。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/356412.html
下一篇:雜七雜八的學習
