A generator function in python uses yield instead of a return. It is considered an iterable. This allows for the function to “pause” itself until it is recalled. Generators save tons of precious memory by only storing the current value its operating with, then discarding it when called again. A very basic example of an even number generator is:
1 2 3 4 5 | def even_num_gen(): x=2 while 1: yield x x+=2 |
Which will end up as an iterable object that can be called like any other iterable:
1 | a = [x for x in even_num_gen() if x < 10000] |
Other sample generators:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #Triangle number generator def triangle_num_gen(): a=1 b=1 while 1: a+=1 b+=a yield b #Fibonacci Generator: def fibonacci_gen(): a=1 b=2 c=2 while 1: yield c c=a+b a=b b=c |
A common way for interfacing with generator objects is using the itertools takewhile() method. As an example. find the sum of all fibonacci numbers under 4000000:
1 2 3 4 5 6 7 8 9 10 11 12 | from itertools import takewhile def fibonacci_gen(): a=1 b=2 c=2 while 1: yield c c=a+b a=b b=c sum(takewhile(lambda x: x <= 4000000,fibonacci_gen())) |
No Comments
Leave some