# 斐波那契数列
# 1,1,2,3,5,8,13....
1)用递归函数实现斐波那契数列:
(指定第几个斐波那契数)
def fib(n): if n == 1 or n == 2: return 1 return fib(n-1)+fib(n-2) print(fib(24))
分解:
# def fib(5): # if 5 == 1 or 5 == 2: # return 1 # return fib(4)+fib(3) # fib(5) = fib(4) + fib(3) # # def fib(4): # if 4 == 1 or 4 == 2: # return 1 # return fib(3)+fib(2) # fib(4) = fib(3) + fib(2) --> 2 + 1 --> 2 # # def fib(3): # if 3 == 1 or 3 == 2: # return 1 # return fib(2)+fib(1) # fib(3)= fib(2) + fib(1) --> 1+1 # # fib (2) = 1 fib(1) = 1