Skip to content

Instantly share code, notes, and snippets.

@pmrowla
Created October 23, 2015 06:21
Show Gist options
  • Save pmrowla/634e7bdf1c1ff9c16fa5 to your computer and use it in GitHub Desktop.
Save pmrowla/634e7bdf1c1ff9c16fa5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''FizzBuzz library'''
from __future__ import unicode_literals
class FizzBuzzError(Exception):
pass
def fizzbuzz(n):
"""FizzBuzz a number
Parameters:
n -- a number
Returns 'Fizz' if n is divisible by 3, 'Buzz' if n is divisible by 5,
'FizzBuzz' if n is divisble by both 3 and 5.
Raises a FizzBuzzError if n is not divisible either 3 or 5.
"""
if not n % 3:
if not n % 5:
return 'FizzBuzz'
return 'Fizz'
elif not n % 5:
return 'Buzz'
else:
raise FizzBuzzError
def fizzbuzz_range(start, stop, step=1):
"""FizzBuzz a range of numbers
Parameters:
start -- the start of the range of numbers to fizzbuzz (inclusive)
stop -- the end of the range of numbers to fizzbuzz (exclusive)
step -- the interval of numbers to fizzbuzz
Returns a list of strings containing the fizzbuzz results
"""
result = []
for i in range(start, stop, step):
try:
result.append(fizzbuzz(i))
except FizzBuzzError:
result.append(unicode(i))
return result
def main():
from argparse import ArgumentParser
parser = ArgumentParser(description='Run fizzbuzz on a range of numbers')
parser.add_argument('start', type=int,
help='Start of the range (inclusive)')
parser.add_argument('stop', type=int,
help='End of the range (exclusive)')
parser.add_argument('step', type=int, nargs='?', default=1)
args = parser.parse_args()
for s in fizzbuzz_range(args.start, args.stop, args.step):
print s
if __name__ == '__main__':
main()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Tests for FizzBuzz library'''
from __future__ import unicode_literals, absolute_import
import unittest
from fancy_fizzbuzz import FizzBuzzError, fizzbuzz, fizzbuzz_range
class TestFizzBuzz(unittest.TestCase):
def test_fizzbuzz(self):
self.assertEqual(fizzbuzz(3), 'Fizz')
self.assertEqual(fizzbuzz(5), 'Buzz')
self.assertEqual(fizzbuzz(15), 'FizzBuzz')
with self.assertRaises(FizzBuzzError):
fizzbuzz(1)
def test_fizzbuzz_range(self):
self.assertEqual(
fizzbuzz_range(1, 6, 1),
['1', '2', 'Fizz', '4', 'Buzz']
)
self.assertEqual(
fizzbuzz_range(10, 20, 5),
['Buzz', 'FizzBuzz']
)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment