Created
September 9, 2014 09:11
-
-
Save calvingiles/23e2133416648157796f to your computer and use it in GitHub Desktop.
Example of yield as filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
An example of using the `yield from` syntax in python 3 and a generator expression than mimics this. | |
""" | |
def yield_only_odd(i): | |
''' | |
Yield i if and only if i is odd. | |
This is a generator that yields zero or one times. | |
''' | |
if i % 2 == 1: | |
yield i | |
def odd_numbers(n): | |
''' | |
Yield odd numbers in the half open set [0,n). | |
''' | |
for i in range(n): | |
yield from yield_only_odd(i) | |
# Demonstration of yield as a filter | |
print(list(odd_numbers(10))) | |
# Demonstration of the same in generator expressions | |
print(list(j for i in range(0, 10, 1) for j in yield_only_odd(i))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment