1、了解斐波那契数列,它是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波纳契数列以如下被以递归的方法定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)。
2、代码实现
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
func()
end_time = time.time()
print("\n")
print(end_time - start_time)
return wrapper
def fib_recur(n):
'''
递归方法实现
'''
if n<=1:
return n
return fib_recur(n-1)+fib_recur(n-2)
def fib_loop(n):
'''
递推方法实现
'''
a,b=0,1
if n == 0 or n == 1:
return n
for i in range(n):
a,b=b,a+b
return a
def fib_loop_while(max):
'''
生成器实现
'''
a, b = 0, 1
while max > 0:
a, b = b, a+b
max -= 1
yield a
@decorator
def test_001():
for i in range(1,35):
print(fib_recur(i),end=",")
@decorator
def test_002():
for i in range(1,100):
print(fib_loop(i),end=",")
@decorator
def test_003():
for i in fib_loop_while(20):
print(i,end=",")
test_001()
test_002()
test_003()
网友评论