非递归解决方案
def fib(n): cur = 1 old = 1 i = 1 while (i < n): cur, old, i = cur+old, cur, i+1 return curfor 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 curfor 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@memoizedef 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 neededfor i in range(100): print(fib(i))print(call_count) #prints 100
这一次, 每个 fibbonacci数计算 恰好
一次,并存储比。因此,该解决方案将胜过所有其他解决方案。但是,装饰器的实现既快速又肮脏,请不要将其投入生产。(有关python装饰器的详细信息,请参见SO上的这个令人惊讶的问题:)
因此,
fib定义后,该程序将类似于(对不起,只是循环很无聊,这是一些更酷的python东西:list
comprehensions)
fib_n = int(input("Fib number?"))fibs = [fib(i) for i in range(fib_n)]print " ".join(fibs)这会在一行中打印所有数字,并用空格分隔。如果您希望每条线都单独显示
" ",请替换为
"n"



