From a48f7877d903b6ad30f85068d09f4f477a4769af Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 30 Nov 2019 12:04:57 +0100 Subject: [PATCH] fizzbuzz: add fizzbuzzer custom function creator --- fizzbuzz/fizzbuzz.py | 27 +++++++++++++++++--------- fizzbuzz/test_fizzbuzz.py | 41 ++++++++++++++++++++++++++++++++------- 2 files changed, 52 insertions(+), 16 deletions(-) diff --git a/fizzbuzz/fizzbuzz.py b/fizzbuzz/fizzbuzz.py index fd586c0..4c01487 100755 --- a/fizzbuzz/fizzbuzz.py +++ b/fizzbuzz/fizzbuzz.py @@ -1,4 +1,20 @@ #! /usr/bin/env python +from typing import Callable, Dict + + +def fizzbuzzer(words: Dict[int, str]) -> Callable[[int], None]: + def _fun(max: int) -> None: + for i in range(1, max + 1): + out = [] + for div, word in words.items(): + if i % div == 0: + out.append(word) + if len(out) > 0: + print("".join(out)) + else: + print(i) + + return _fun def fizzbuzz(max: int = 100) -> None: @@ -6,15 +22,8 @@ def fizzbuzz(max: int = 100) -> None: 3: "fizz", 5: "buzz", } - for i in range(1, max + 1): - out = [] - for div, word in words.items(): - if i % div == 0: - out.append(word) - if len(out) > 0: - print("".join(out)) - else: - print(i) + f = fizzbuzzer(words) + f(max) if __name__ == "__main__": diff --git a/fizzbuzz/test_fizzbuzz.py b/fizzbuzz/test_fizzbuzz.py index 7e2a75c..c4b2c9c 100644 --- a/fizzbuzz/test_fizzbuzz.py +++ b/fizzbuzz/test_fizzbuzz.py @@ -1,26 +1,30 @@ -from fizzbuzz import fizzbuzz +from fizzbuzz import fizzbuzz, fizzbuzzer -def list_output(max, capsys, expected_list): - fizzbuzz(max) +def list_output(max, capsys, expected_list, function): + function(max) out, __ = capsys.readouterr() 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): - list_output(2, capsys, [1, 2]) + list_fizzbuzz_output(2, capsys, [1, 2]) 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): - 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): - list_output( + list_fizzbuzz_output( 15, capsys, [ @@ -41,3 +45,26 @@ def test_fizzbuzz_shows_fizzbuzz_on_fifteen(capsys): "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", + ], + )