Created
May 4, 2014 03:14
-
-
Save poundifdef/f6fedd14734c0872f1f5 to your computer and use it in GitHub Desktop.
FizzBuzz in Enterprise Python
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
#!/usr/bin/python | |
# | |
# To run: `python crackle.py` | |
# To run tests: `python -m unittest crackle` | |
from collections import defaultdict | |
import unittest | |
def crackle_popper(): | |
"""Generator which will infinitely crackle and pop""" | |
i = 0 | |
# Clever way to have an infinite generator | |
for x in iter(int, 1): | |
i += 1 | |
rc = i | |
if i % 15 == 0: | |
rc = 'CracklePop' | |
elif i % 3 == 0: | |
rc = 'Crackle' | |
elif i % 5 == 0: | |
rc = 'Pop' | |
# return both the iterator position and the sound | |
yield (i, rc) | |
class TestCrackler(unittest.TestCase): | |
def test_crackler(self): | |
"""Basic test to see if our crackler works""" | |
# How big do we want our test to be? | |
crackle_range = 10000 | |
# Calculate some expected values | |
expected_cracklepops = crackle_range / 15 | |
expected_crackles = crackle_range/3 - expected_cracklepops | |
expected_pops = crackle_range/5 - expected_cracklepops | |
# Set up some temporary variables and our crackler | |
crackle_counter = defaultdict(int) | |
x = crackle_popper() | |
# Collect crackle data | |
for i in xrange(1, crackle_range + 1): | |
iterator_location, sound = x.next() | |
if sound in ['Crackle', 'Pop', 'CracklePop']: | |
crackle_counter[sound] += 1 | |
# Make sure expected == actual | |
self.assertEquals(crackle_counter['Crackle'], expected_crackles) | |
self.assertEquals(crackle_counter['Pop'], expected_pops) | |
self.assertEquals(crackle_counter['CracklePop'], expected_cracklepops) | |
if __name__ == '__main__': | |
x = crackle_popper() | |
# We want to call next() on this generator 100 times. | |
for i in xrange(1, 101): | |
iterator_location, sound = x.next() | |
print sound |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment