In [1]:
# This is for rerunning cells without restarting kernel.
try:
del fizzbuzz
except NameError:
pass
In [2]:
# Let's setup some ad-hoc testing.
expected_outputs = {
1*3: 'Fizz',
2*3: 'Fizz',
1*5: 'Buzz',
2*5: 'Buzz',
3*5: 'FizzBuzz',
16: str(16),
}
In [3]:
def test():
"""Ad-hoc testing"""
for input_, expected_output in expected_outputs.items():
actual_output = fizzbuzz(input_)
assert expected_output == actual_output
return 'All tests passed.'
In [4]:
# Tests should crash,
# since the code they test does not exist (yet).
test()
In [5]:
# This is written to provoke test failures.
def fizzbuzz(i):
return 'hello world'
In [6]:
# Should crash
test()
In [7]:
def fizzbuzz(i):
terms = []
if i % 3 == 0:
terms.append('Fizz')
if i % 5 == 0:
terms.append('Buzz')
if not terms:
terms.append(str(i))
return ''.join(terms)
In [8]:
# tests should pass.
test()
Out[8]:
In [9]:
def foo(n):
for i in range(1, n+1):
print(fizzbuzz(i))
In [10]:
foo(20)
In [11]:
# Let's modify fizzbuzz for FizzBuzzBurr,
# where Burr is for multiples of 7.
expected_outputs = {
1*3: 'Fizz',
2*3: 'Fizz',
1*5: 'Buzz',
2*5: 'Buzz',
1*7: 'Burr',
2*7: 'Burr',
3*5: 'FizzBuzz',
3*7: 'FizzBurr',
5*7: 'BuzzBurr',
3*5*7: 'FizzBuzzBurr',
16: str(16),
}
def fizzbuzz(i):
return None
# Tests should fail.
test()
In [12]:
# Now for real code. Tests should pass.
modulus_words = (
(3, 'Fizz'),
(5, 'Buzz'),
(7, 'Burr'),
)
def fizzbuzz(i):
terms = []
for modulus, word in modulus_words:
if i % modulus == 0:
terms.append(word)
if not terms:
terms.append(str(i))
return ''.join(terms)
test()
Out[12]:
In [13]:
n = 3 * 5 * 7 + 3
n = 20
foo(n)
In [14]:
# Play with trying list comprehension instead of for loop.
modulus_words = (
(3, 'Fizz'),
(5, 'Buzz'),
(7, 'Burr'),
)
def fizzbuzz(i):
terms = [
word
for modulus, word in modulus_words
if i % modulus == 0
]
if not terms:
terms.append(str(i))
return ''.join(terms)
test()
Out[14]:
Ignore the stuff below. It is an unfinished thought.
In [ ]:
# Enhance test() to show helpful info for failed tests.
# This is unfinished.
def test():
"""Ad-hoc testing"""
for input_, expected_output in expected_outputs.items():
actual_output = fizzbuzz(input_)
try:
assert expected_output == actual_output
except AssertionError:
print(
'ERROR got %r instead of %r for fizzbuzz(%r)' %
(actual_output, expected_output, input_))