方法一 :函数闭包
- #定义斐波那契数列函数
- def fib(x):
- back1 , back2 = 1,1
- def get_fib():
- nonlocal back1 , back2
- back1 , back2 = back2 , back1+back2
- print(back1,end = "")
- return get_fib
- n = int(input('请输入需要几位斐波那契数列:'))
- # 利用函数闭包调用斐波那契函数
- def my_fib(n):
- f = fib()
- for i in range(n):
- f()
- my_fib(n)
-
方法二:迭代方法
- def func(n):
- a = 1
- b = 1
- c = 1
- # 1,1,2 a=1 , b = 1 c = a+b 然后往后挪
- while n > 2:
- c = a + b
- a = b
- b = c
- n -= 1
- print(c)
- func(5)
方法三:递归函数
- def fib(n):
- if n == 1 or n == 2:
- return 1
- else:
- return fib(n-1) + fib(n-2)
-
- fib(5)
方法四:效率更高
- def tailFibRec(n,x,y):
- if n == 1 or n == 2:
- return y
- else:
- return tailFibRec(n-1,y,x+y)
- tailFibRec(12,1,1)
利用timeit测量几种方法耗费的时间
- # 导入timeit
- import timeit
-
- def fibRecur(n):
- if n == 1 or n == 2:
- return 1
- else:
- return fibRecur(n-1) + fibRecur(n-2)
-
- def tailFibRecur(n, x, y):
- if n == 1 or n == 2:
- return y
- else:
- return tailFibRecur(n-1, y, x+y)
-
- def fibIter(n):
- a, b, c = 1, 1, 1
- while n > 2:
- c = a + b
- a = b
- b = c
- n -= 1
- return c
- FR = timeit.timeit("fibRecur(12)",setup = "from __main __ import fibRecur")
- print(f"普通递归函数调用的时间:{FR.2f}秒)"