Fibonacci Series (Golden section) refers to such a sequence of 0, 1, 1, 2, 3, 5, 8, 13, in particular: the No. 0 item is 0, the 1th item is the first 1. Starting with the third item, each item is equal to the sum of the first two items. Python implements the Fibonacci sequence code as follows: Implement one:
1 defFibonacci ():2num = input ("Please input your number\n")3i,a,b= 0,0,1//Assign Value4 ifint (num) <0:5 Print("The data you entered is not reasonable.")6 elifint (num) = = 1:7 Print(a)8 Else:9 whileI <int (num):Ten Print(a) One #sum = a+b A #A = b - #b = Sum -A, B = B, A + b#A, B = B, A + B cannot be written as A=b B=a+b, and if written like this, B is not a value added by the first two bits, but the sum of a and b that have been assigned a value by B . theI+=1 -Fibonacci ()Implementation two: The way to use the list
1 def Fibonacci (num): 2 fibs = [0,1]3for in Range (num-2):4 fibs.append (Fibs[-2]+fibs[-1]) # The result of the second-to-last + countdown number, appended to the list 5 Print (fibs) 6 7 Fibonacci (5)
Implementation of the three: the two methods are directly called in the function of print printing, return value is none, and therefore cannot be reused. Return is a sequence that can be reused directly.
1 def Fibonacci (num): 2 fibs = [0,1]3for in Range (num-2):4 fibs.append (Fibs[-2]+fibs[-1]) # The result of the second-to-last + countdown number, appended to the list 5 return (fibs) 6 Fibonacci (5)
Or
1 def Fab_demo2 (max): 2 A, n, b = 0, 0, 13 List_demo = [] 4 while n < max: 5 List_demo.append (b) 6 A, B = B, a + b 7 n + = 18
print
(List_demo)
9
return list_demo
Implementation of four: can be reused, but considering the late to store in the list of data too large, compared to eat memory wasted resources, should do, at this time, considering the use of iterable we can rewrite the FAB function as a support iterable class
1 classFab (object):2 def __init__(Self,max):3Self.max =Max4SELF.N, SELF.A, self.b = 0, 0, 15 6 def __iter__(self):#inherit object, override __iter__, automatically call __next__ method, return R object7 return Self8 9 def __next__(self):#here Python2 for Next,python3 for __next__, note the differenceTen ifSELF.N <Self.max: OneR =self.b ASELF.A, self.b = self.b, SELF.A +self.b -SELF.N + = 1 - returnR the Raisestopiteration () - #The Fab class continuously returns the next number of columns through next (), and memory consumption is always constant: - forIinchFab (5): - Print(i) + #or - Print(Next (ITER (Fab (5)))
Implementation Five
Code is not concise, use the yield keyword
1 defFab_demo4 (max):2A,n,b = 0,0,13 whileN <Max:4 yieldb5#Printb6A, B = b,a+b7N+=18 Print(Next (Fab_demo4 (5)))9 forIinchFab_demo4 (5):Ten Print(i)
Just change print B to yield B, and get the iterable effect while keeping it simple. The effect of yield is to turn a function into a generator, the function with yield is no longer a normal function, and the Python interpreter treats it as a G Enerator, calling Fab (5) does not execute the FAB function, but returns a Iterable object! When the For loop executes, each loop executes the code inside the FAB function, and when it executes to yield B, the FAB function returns an iteration value, and the next iteration, the code proceeds from the next statement of Yield B, and the local variable of the function looks exactly the same as before the last break, so the function Continue execution until yield is encountered again. You can also call the next () Method of Fab (5) Manually (because Fab (5) is a generator object that has the next () method)
We can draw the following conclusions:
A function with yield is a generator, which, unlike a normal function, generates a generator that looks like a function call, but does not execute any function code until it calls next () (which is automatically called next () in the For loop) to begin execution. Although the execution process still executes according to the process of the function, each execution to a yield statement is interrupted and an iteration value is returned, and the next execution proceeds from the next statement of yield. It looks as if a function was interrupted several times by yield during normal execution, and each break returns the current iteration value through yield.
The benefits of yield are obvious, and the ability to rewrite a function into a generator yields an iterative capability that computes the value of the next next () rather than the instance of the class, not only the code is concise, but the execution process is exceptionally clear.
How can I tell if a function is a special generator function? You can use Isgeneratorfunction to judge:
1 from Import isgeneratorfunction 2 >>> isgeneratorfunction (FAB)3 True
To distinguish between Fab and fab (5), Fab is a generator function, and fab (5) is a generator returned by a call to fab, like the definition of a class and the difference between an instance of a class:
Fibonacci Sequence-python Implementation