fizzbuzz: add fizzbuzzer custom function creator

This commit is contained in:
Bruno BELANYI 2019-11-30 12:04:57 +01:00
parent 6159d12cff
commit a48f7877d9
2 changed files with 52 additions and 16 deletions

View file

@ -1,11 +1,9 @@
#! /usr/bin/env python #! /usr/bin/env python
from typing import Callable, Dict
def fizzbuzz(max: int = 100) -> None: def fizzbuzzer(words: Dict[int, str]) -> Callable[[int], None]:
words = { def _fun(max: int) -> None:
3: "fizz",
5: "buzz",
}
for i in range(1, max + 1): for i in range(1, max + 1):
out = [] out = []
for div, word in words.items(): for div, word in words.items():
@ -16,6 +14,17 @@ def fizzbuzz(max: int = 100) -> None:
else: else:
print(i) print(i)
return _fun
def fizzbuzz(max: int = 100) -> None:
words = {
3: "fizz",
5: "buzz",
}
f = fizzbuzzer(words)
f(max)
if __name__ == "__main__": if __name__ == "__main__":
fizzbuzz() fizzbuzz()

View file

@ -1,26 +1,30 @@
from fizzbuzz import fizzbuzz from fizzbuzz import fizzbuzz, fizzbuzzer
def list_output(max, capsys, expected_list): def list_output(max, capsys, expected_list, function):
fizzbuzz(max) function(max)
out, __ = capsys.readouterr() out, __ = capsys.readouterr()
assert out == "\n".join(map(lambda x: str(x), expected_list)) + "\n" assert out == "\n".join(map(lambda x: str(x), expected_list)) + "\n"
def list_fizzbuzz_output(max, capsys, expected_list):
list_output(max, capsys, expected_list, fizzbuzz)
def test_fizzbuzz_counts_to_two(capsys): def test_fizzbuzz_counts_to_two(capsys):
list_output(2, capsys, [1, 2]) list_fizzbuzz_output(2, capsys, [1, 2])
def test_fizzbuzz_shows_fizz_on_three(capsys): def test_fizzbuzz_shows_fizz_on_three(capsys):
list_output(3, capsys, [1, 2, "fizz"]) list_fizzbuzz_output(3, capsys, [1, 2, "fizz"])
def test_fizzbuzz_shows_buzz_on_five(capsys): def test_fizzbuzz_shows_buzz_on_five(capsys):
list_output(5, capsys, [1, 2, "fizz", 4, "buzz"]) list_fizzbuzz_output(5, capsys, [1, 2, "fizz", 4, "buzz"])
def test_fizzbuzz_shows_fizzbuzz_on_fifteen(capsys): def test_fizzbuzz_shows_fizzbuzz_on_fifteen(capsys):
list_output( list_fizzbuzz_output(
15, 15,
capsys, capsys,
[ [
@ -41,3 +45,26 @@ def test_fizzbuzz_shows_fizzbuzz_on_fifteen(capsys):
"fizzbuzz", "fizzbuzz",
], ],
) )
def test_can_foobarbazz_customization(capsys):
foobarbazz = fizzbuzzer({2: "foo", 3: "bar", 4: "bazz"})
list_output(
function=foobarbazz,
max=12,
capsys=capsys,
expected_list=[
1,
"foo",
"bar",
"foobazz",
5,
"foobar",
7,
"foobazz",
"bar",
"foo",
11,
"foobarbazz",
],
)