非递归解决方案
def fib(n):
cur = 1
old = 1
i = 1
while (i < n):
cur, old, i = cur+old, cur, i+1
return cur
for i in range(10):
print(fib(i))
发电机解决方案:
def fib(n):
old = 0
cur = 1
i = 1
yield cur
while (i < n):
cur, old, i = cur+old, cur, i+1
yield cur
for f in fib(10):
print(f)
请注意,生成器解决方案优于非递归解决方案(如果记忆化不适用于递归解决方案,非递归优于递归解决方案)
再一次,用记忆递归:
def memoize(func):
memo = dict()
def decorated(n):
if n not in memo:
memo[n] = func(n)
return memo[n]
return decorated
@memoize
def fib(n):
#added for demonstration purposes only - not really needed
global call_count
call_count = call_count + 1
#end demonstration purposes
if n<=1:
return 1
else:
return fib(n-1) + fib(n-2)
call_count = 0 #added for demonstration purposes only - not really needed
for i in range(100):
print(fib(i))
print(call_count) #prints 100
这一次每个斐波那契数只计算一次,然后存储。因此,此解决方案将胜过所有其他解决方案。然而,装饰器的实现既快又脏,不要让它进入生产环境。(有关 python 装饰器的详细信息,请参阅 SO 上的这个惊人的问题:)
因此,fib
定义后,程序将类似于(抱歉,只是循环很无聊,这里有一些更酷的 python 东西:列表推导)
fib_n = int(input("Fib number?"))
fibs = [fib(i) for i in range(fib_n)]
print " ".join(fibs)
这将打印一行中的所有数字,以空格分隔。如果您希望每个都在自己的行上 - 替换" "
为"\n"