斐波那契数列递归数学定义如下:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)
Python代码:
函数f(n),输入非负整数n,返回f[n]
def f(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a + b
return a
函数返回值:
print(f(1)) # 1
print(f(2)) # 1
print(f(3)) # 2
print(f(10)) # 55
上述代码来自:http://stackoverflow.com/questions/15047116/a-iterative-algorithm-for-fibonacci-numbers
函数fib(n),输入非负整数n,返回fibs数组
def fib(n):
if n == 1:
return [1]
if n == 2:
return [1, 1]
fibs = [1, 1]
for i in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs
函数返回值:
print(fib(1)) # [1]
print(fib(2)) # [1, 1]
print(fib(3)) # [1, 1, 2]
print(fib(10)) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
上述代码来自:http://edumaven.com/python-programming/non-recursive-fibonacci
本文链接:http://bookshadow.com/weblog/2014/12/01/python-non-recursive-fibonacci/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。