Quick actions

cmd+k|ctrl+k

Navigation

Languages

PI. Yield produces values on request

Snippet info

Language

Python

Visibility

public

Author

weralwolf

Created

2015-08-10T18:13:19Z

Updated

2015-08-10T18:13:19Z

# More on Fibonacci sequence: https://en.wikipedia.org/wiki/Fibonacci_number
# Here we're writing generator. What is that?
#
# Ok, using simple words of mortal generator is an object that produces 
# result by result saving its state in between yields.
#
# More delighted explanation tells us that generators are forward iterators that
# does not store values, but produce them storing its state inbetween of calls.
#
# Full anwer could be found here: http://stackoverflow.com/a/231855
def fib(n):
    # We initialte state of iterator here.
    a, b = 0, 1
    while a < n:
        # Now we're doing some cruel magic, because right now execution of this 
        # function stops, we give execution power back to user yielding him
        # intermediate result.
        yield b
        # But when user will require next value we would start execution from
        # right here and back to while loop as we have never stop looping around.
        a, b = b, a + b

# Let's lamely calculate sum of first 100 fibonac numbers.
sum = 0
for i in fib(100):
    sum += i

print(sum)
INFO