First, repeat selected cells from 20170921-dojo-fizzbuzz-revisited.
In [1]:
# This is for rerunning cells without restarting kernel.
try:
del fizzbuzz
except NameError:
pass
In [2]:
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 [3]:
# Tests should crash,
# since the code they test does not exist (yet).
test()
In [4]:
# This is written to provoke test failures.
def fizzbuzz(i):
return 'hello world'
In [5]:
# Should crash
test()
In [6]:
# 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 [7]:
# 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[7]:
Now we add new stuff.
In [8]:
# Use "or" operator like Neil Ludbad used at monthly meeting
# to eliminate an if statement.
modulus_words = (
(3, 'Fizz'),
(5, 'Buzz'),
(7, 'Burr'),
)
def fizzbuzz(i):
terms = [
word
for modulus, word in modulus_words
if i % modulus == 0
]
return ''.join(terms) or str(i)
test()
Out[8]:
In [9]:
# Consolidate to one big expression.
# It is hard to read, so I do not like it.
modulus_words = (
(3, 'Fizz'),
(5, 'Buzz'),
(7, 'Burr'),
)
def fizzbuzz(i):
return ''.join(
word
for modulus, word in modulus_words
if i % modulus == 0
) or str(i)
test()
Out[9]:
Let's try multiples of non-primes 4, 6, and 15.
In [10]:
expected_outputs = {
1*4: 'Fizz',
2*4: 'Fizz',
1*6: 'Buzz',
2*6: 'FizzBuzz',
1*15: 'Burr',
2*15: 'BuzzBurr',
4*6: 'FizzBuzz',
4*15: 'FizzBuzzBurr',
6*15: 'BuzzBurr',
4*6*15: 'FizzBuzzBurr',
5: str(5),
}
def fizzbuzz(i):
return None
# Tests should fail.
test()
In [11]:
modulus_words = (
(4, 'Fizz'),
(6, 'Buzz'),
(15, '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[11]: