Functions - Advanced Functions - Fibonacci

As we said before, generator algorithm is saved, next (g) to calculate the value of the next element g of each call, until the calculated to the last element, no more elements, throw stopIteration error

Of course, above this constant call next (g) is too sick, the correct approach is to use a for loop, because the generator is iterable:

>>> g = (x*x for x in range(10))
>>> for n in g:
...  print(n)
...
0
1
4
9
16
25
36
49
64
81
>>>

So, we created after a generator, basically never call next (), but for loop to iterate through it, and do not care about StopIteration errors.

generator is very powerful. If the projection algorithm is complex, when a similar list with the formula for loop can not be achieved, it can also be implemented as a function.

For example, the well-known Fibonacci (the Fibonacci), except for the first and second number, any number can be obtained by the first two numbers together:

1,1,2,3,5,8,13,21,34,。。。。

Fibonacci column with a list of Formula write to, however, use the function print it out very easily:

 

DEF FIB (max): 
n- , A , B = 0 , 0 , . 1 the while n-<max: Print (B) A , B = B , A + B n-= n-+ . 1 return 'DONE'






note assignment:
A , b = b, a + b

def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a+b
n = n + 1
return 'done'

print(fib(10))
执行结果:
<generator object fib at 0x00000200080FAA98>


def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a+b
n = n + 1
return 'done'
f = fib(10)
print(fib(10))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))

执行结果:
<generator object fib at 0x000001EEC0AAAB88>
1
1
2
3
5
8

for i in f:
  print (i)
Results of:
<Object Generator FIB AT 0x00000261EB7EAB88>
. 1
. 1
2
. 3
. 5
. 8
13 is
21 is
34 is
55

the yield during the execution of the function B # freeze in this step, the value of B and returned to the outside next ()

Guess you like

Origin www.cnblogs.com/kingforn/p/10937424.html