抱歉,如果這是一個菜鳥問題,我無法在線找到解決方案(也許我只是不知道要搜索什么)。
如何從此遞回函式回傳“找到”字典(我只能回傳第 n 個數字)
注意:由于多種原因,在末尾簡單地回傳發現不起作用
# Nth Fibonacci number generator
def nth_Rfib(n, found = {0:1, 1:1}):
if n in found:
return found[n]
else:
found[n] = nth_Rfib(n-1, found) nth_Rfib(n-2, found)
#print(found)
return found[n] # return found ** Doesn't Work **
print(nth_Rfib(5)) # 8
# instead, it should return: {0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}
謝謝你。
uj5u.com熱心網友回復:
在這兩種情況下,您都需要回傳found. 但是當您的函式回傳字典時,您需要在遞回呼叫它時訪問所需的值:
def nth_Rfib(n, found = {0:1, 1:1}):
if n in found:
return found
else:
found[n] = nth_Rfib(n-1, found)[n-1] nth_Rfib(n-2, found)[n-2]
return found
print(nth_Rfib(5))
這回傳:
{0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}
請注意默認可變引數(例如 your )可能存在的問題found = {0:1, 1:1},例如:
>>> print(nth_Rfib(3))
{0: 1, 1: 1, 2: 2, 3: 3}
>>> print(nth_Rfib(5))
{0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}
>>> print(nth_Rfib(3))
{0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}
nth_Rfib(3)afternth_Rfib(5)回傳相同的字典,因為您從未將其重置為 default {0:1, 1:1}。
uj5u.com熱心網友回復:
您需要一個回傳數字的函式,以便遞回運算式
found[n] = fib(n-1) fib(n-2)
可以說得通;而且您還需要一個回傳字典的函式,因為這最終是您想要回傳的。
因此定義兩個不同的函式是有意義的,一個回傳一個數字,一個回傳一個字典。
def nth_Rfib(n):
found = {0: 0, 1: 1}
def fib(n):
if n not in found:
found[n] = fib(n-1) fib(n-2)
return found[n]
fib(n)
return found
這會found生成一個區域變數nth_Rfib,但在 的遞回呼叫期間充當全域變數fib。
它還完全消除了可變默認引數的任何奇怪之處。
>>> nth_Rfib(10)
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13, 8: 21, 9: 34, 10: 55}
>>> nth_Rfib(3)
{0: 0, 1: 1, 2: 1, 3: 2}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/520599.html
標籤:Python递归斐波那契
