Skip to content

Instantly share code, notes, and snippets.

@olooney
Created November 8, 2013 14:28
Show Gist options
  • Save olooney/7371763 to your computer and use it in GitHub Desktop.
Save olooney/7371763 to your computer and use it in GitHub Desktop.
"""
Example using Python's itertools and generators to implement the classic FizzBuzz problem using pythonic iterators.
Output looks like this:
$ python fizz_buzz_with_iterator.py
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
"""
from itertools import cycle, chain, izip, islice, count
def make_cycle(n, word):
"""returns an infinite iterator which returns the given word every n-th time and an empty string every other time:
make_cycle(3, 'test') -> 'test', '', '', 'test', '', '', ...
"""
return cycle( chain([word], ['']*(n-1)) )
def concat_or_index(*iterators):
"""returns an iterator that loops through all the provided iterators
simultaneously and returns the concatination of all their values... unless
the concatination is considered False, in which case it returns the index
instead.
"""
for row in izip(count(), *iterators):
index = row[0]
result = ''.join(row[1:])
yield result or index
if __name__ == '__main__':
# demo of the functionality using the classic 3/5 FizzBuzz Problem
endless_fizz_buzz = concat_or_index(make_cycle(3, 'Fizz'), make_cycle(5, 'Buzz'))
# note that we have to skip the 0th element because the classic problem specifies
# output starting from the
for result in islice(endless_fizz_buzz, 1, 21):
print result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment