以生成第 n 个斐波那契数为例,开始学习有关动态编程和记忆的知识。我编写了以下代码(实际上是从网站获得帮助),将其删除并尝试自己编写一次。我无法理解的返回调用(TypeError)有问题。
我通过缩进 if 语句下方的返回备忘录[x] 调用来修复此问题,并且程序可以正常工作。
我只想在以下代码中了解错误的原因:
代码有什么作用?
1)创建一个函数来记住输入函数
2)子函数“ helper”,它检查输入函数的输出是否在名为“ memo”的字典中。如果没有,它将根据需要更新字典
整个函数从备忘录中返回一个数字(如果已经在备忘录中),以避免不必要的分支。
3)创建一个使用递归算法生成斐波那契数的函数。
4)记忆Fib编号生成器并打印 nth Fib编号
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper
def fib(n):
if n==0:
return 0
if n == 1:
return 1
else:
return fib(n-1)+fib(n-2)
fib = memoize(fib)
print(fib(10))
我希望它返回 nth Fib。否。但是相反,它在返回备忘录[x] 调用中返回错误。
错误消息:
Traceback (most recent call last):
File "E:\euler25.py", line 18, in <module>
print(fib(10))
File "E:\euler25.py", line 5, in helper
memo[x] = f(x)
File "E:\euler25.py", line 14, in fib
return fib(n-1)+fib(n-2)
File "E:\euler25.py", line 5, in helper
memo[x] = f(x)
File "E:\euler25.py", line 14, in fib
return fib(n-1)+fib(n-2)
File "E:\euler25.py", line 5, in helper
memo[x] = f(x)
File "E:\euler25.py", line 14, in fib
return fib(n-1)+fib(n-2)
File "E:\euler25.py", line 5, in helper
memo[x] = f(x)
File "E:\euler25.py", line 14, in fib
return fib(n-1)+fib(n-2)
File "E:\euler25.py", line 5, in helper
memo[x] = f(x)
File "E:\euler25.py", line 14, in fib
return fib(n-1)+fib(n-2)
File "E:\euler25.py", line 5, in helper
memo[x] = f(x)
File "E:\euler25.py", line 14, in fib
return fib(n-1)+fib(n-2)
File "E:\euler25.py", line 5, in helper
memo[x] = f(x)
File "E:\euler25.py", line 14, in fib
return fib(n-1)+fib(n-2)
File "E:\euler25.py", line 5, in helper
memo[x] = f(x)
File "E:\euler25.py", line 14, in fib
return fib(n-1)+fib(n-2)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
[Finished in 0.1s with exit code 1]
此错误消息是什么意思?
答案 0 :(得分:3)
您对备注功能的return
语句范围有疑问:
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
# function should return always the memoized value
return memo[x]
return helper
问题在于,您的helper
函数在某个时候返回了None
,这使fib函数试图在+
和int
之间{ ,它会触发None
这里有live example