<>python Using recursion to realize Fibonacci sequence

python Using recursion to realize Fibonacci sequence

<> Let's get to know first

Fibonacci sequence （Fibonacci sequence）, Also known as golden section series , Because the mathematician Leonardo · Fibonacci （Leonardoda
Fibonacci） Take rabbit breeding as an example , So it is also called “ Rabbit Series ”, It refers to such a sequence ：0,1,1,2,3,5,8,13,21,34,…… In Mathematics , Fibonacci sequence is defined recursively as follows ：F(0)=0,F(1)=1,
F(n)=F(n - 1)+F(n - 2)（n ≥ 2,n ∈ N） In modern physics , Quasicrystal structure , Chemistry and other fields , Fibonacci sequence has direct application , to this end , American Mathematics Association
1963 It has been published since 《 Fibonacci series Quarterly 》 A mathematics magazine named , It is used to publish the research results in this field .*

Use recursion to return before n Fibonacci sequence of terms ：

<>func_1(n-2)+func_1(n-1) This code is the main code of this section

def func_1(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return func_1(n-2)+func_1(n-1)
hypothesis n take 4
return func_1(2)+func_1(3)
func_1(2) If the function is brought in, the 1,func_1(3) If the function is brought in, the func_1(3-2)+func_1(3-1) mean
func_1(1)+func_1(2) , The brought in function is 1+1 So I came to the conclusion func_1(4)
=func_1(2)+func_1(3)=func_1(2)+func_1(1)+func_1(2)=3

<> The recursive function just now can only return the second n Each value , If you want to go back before n Item value , You have to build a function around you to add the values one by one

code implementation ：
def func(a):
def func_1(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return func_1(n-2)+func_1(n-1)
list_1 = []
for i in range(a):
list_1.append(func_1(i))
return list_1

print(func(20))

<> I wish you all the best Python Study smoothly !

Technology
Daily Recommendation
views 12
views 5
views 5
views 4