Friday, August 25, 2017

python generator and yield

Generators are best for calculating large sets of results (particularly calculations involving loops themselves) where you don’t want to allocate the memory for all results at the same time.

To understand generator and yield, we can debug the code below.

put break point at line 5,6 and 10
  1. when the code is executed, line 9, it calls fibon(10) to get x
  2. the fibon function is executed to line 5, yield a, it suspends the process of fibon and return to the main process, x gets the value of a.
  3. Then line 10, print(x), we can have code here which consumes system resources here.
  4. Once it is done, it goes back to line 9, for x in fibon(10), ask for next value from fibon function
  5. It goes to line 6, the place where it is suspended, run the calculation, continue the iteration to line 4, 5 yield again, it will pop the calculated value to the main process line 10 again.
Send method
to send the value into the function

No comments:

Post a Comment