即使有记忆,我也无法计算斐波那契(1000)。这是我的代码(与关于memoization的教科书示例相同)。
Flask-SQLAlchemy==2.2
Flask==0.12.2
SQLAlchemy==1.1.13
我得到的错误:
inputnumber = 10000 # the error starts if n > 998
existingvalues = {}
def fib_series(n):
if(n <= 1):
return n
else:
if(n in existingvalues):
value = existingvalues[n]
else:
value = fib_series(n-1) + fib_series(n-2)
existingvalues[n] = value
return value
我想要这样做的原因是比较递归和迭代之间的性能。以下代码进行迭代并且可以找到n>的fibonacci。 1000在几乎相似的时间。
Traceback (most recent call last):
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 24, in <module>
print(fib_series(inputnumber))
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 18, in fib_series
value = fib_series(n-1) + fib_series(n-2)
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 18, in fib_series
value = fib_series(n-1) + fib_series(n-2)
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 18, in fib_series
value = fib_series(n-1) + fib_series(n-2)
[Previous line repeated 994 more times]
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 12, in fib_series
if(n <= 1):
RecursionError: maximum recursion depth exceeded in comparison
在比较这两种加法技术(递归与迭代)时,是否有与O(复杂性)相关的内容?