Python中的斐波那契记忆

时间:2019-01-09 20:54:45

标签: python fibonacci memoization

我写了这段代码来计算第n个斐波那契数,它可以工作(计算正确的数),但是由于表未更新而失败。有人知道为什么吗?

# memoization
n = 12
table = np.ones(n+1)*-1
def fib3(n):
    if table[n]==-1:
        if n<=2:
            table[n] = 1
        else:
            table[n] = fib3(n-1)+fib3(n-2)
    #return table ##This was part of my original solution but I removed it because it wasn't working
fib3(12)

这是我认为是由于未更新表(因为table [n]始终= -1)引起的错误:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

2 个答案:

答案 0 :(得分:1)

您没有明确返回任何内容,因此您的fib3函数会自动返回None。因此,您的行table[n] = fib3(n-1) + fib3(n-2)的值为table[n] = None + None,并且没有为+定义None运算符。

答案 1 :(得分:0)

您错过了返回fib3函数的值

import numpy as np

# memoization
n = 12
table = np.ones(n+1)*-1
def fib3(n):
    if table[n]==-1:
        if n<=2: 
            table[n] = 1
        else:
            table[n] = fib3(n-1)+fib3(n-2)
    return table[n]
fib3(12)

144