Question: Fibonacci series.
Program analysis: the Fibonacci sequence, also known as the Golden series, refers to a series like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ,.......
In mathematics, the Fibonacci sequence is defined by recursion:
F0 = 0 (n = 0)
F1 = 1 (n = 1)
Fn = f [n-1] + F [N-2] (n => 2)
---------------------
Method 1: Recursive Computing
1 def fibonacci(month): 2 if month == 1: 3 return 1 4 elif month == 2: 5 return 1 6 else: 7 return fibonacci(month-1)+fibonacci(month-2) 8 9 a =fibonacci(35)10 print(a)
Method 2: Use the WHILE LOOP
1 def FAB (n): 2 n1 = 1 3 n2 = 1 4 N3 = 0 5 if n <1: # conditional judgment, if n <, will directly return-1 6 Return-1 7 while (n-2)> 0: 8 N3 = N1 + N2 9 n1 = n210 n2 = n311 N-= 112 return n313 14 N = FAB (20) 15 print (N)
To change it to output a specified number of Fibonacci series, you only need to return the results to the list, which can be directly counted.
1 def fib(n): 2 if n == 1: 3 return [1] 4 if n == 2: 5 return [1,1] 6 fibs = [1,1] 7 for i in range(2,n): 8 fibs.append(fibs[-1]+fibs[-2]) 9 return fibs10 11 print(fib(5))
Exercise 6: Fibonacci Series)