0
我需要計算從n到0的道路數量,但我的代碼似乎適用於某些情況,有些則不適用。Python中的道路計算(遞歸)
編輯: 當我嘗試執行:道路(7,2,3) 它表明:
線95是在末端
Traceback (most recent call last):
File "python", line 102, in <module>
File "python", line 95, in roads
File "python", line 95, in roads
File "python", line 95, in roads
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
def jumps(n, j):
if n == 0:
return True
elif n<0:
return False
else:
if n<j:
return False
elif n==j:
return True
elif n>j:
if n%j ==0:
return True
else:
return False
def roads(n, short_jump, long_jump, memo=None):
if memo == None:
memo = {}
if n not in memo:
if n==0:
memo[n] = 1
return memo[n]
elif n<0:
memo[n] = 0
return memo[n]
else:
sum_hmrm = 0
a = jumps(n, short_jump)
b = jumps(n, long_jump)
c = n-long_jump
d = n-short_jump
if a == True:
sum_hmrm += 1
if b == True:
sum_hmrm += 1
sum_hmrm += (roads(c, short_jump, long_jump, memo) + roads(d, short_jump, long_jump, memo))
memo[n] = sum_hmrm
return memo[n]
_Which_是爲它做的病例和沒有按不工作? – senshin
道路(2,2,3)工程 道路(7,2,3)不工作 我認爲我的問題發生在(n> long_jump)時,但我無法弄清楚爲什麼 – boku666
你是什麼意思「不工作」?它會永遠運行嗎?引發異常?回答錯誤的答案(以及你如何知道正確答案)? – Blckknght