Last active
October 10, 2021 03:43
-
-
Save quanon/0a8b35834ce6d82f67d91aa5f50554d0 to your computer and use it in GitHub Desktop.
Python の doctest を試してみる。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import itertools | |
from collections.abc import Iterator | |
def fizzbuzz(n: int) -> Iterator[int | str]: | |
''' | |
Return the fizzbuzz of n, an exact integer >= 0. | |
>>> from fizzbuzz import fizzbuzz | |
>>> [i for i in fizzbuzz(15)] | |
[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz'] | |
>>> from collections.abc import Iterator | |
>>> isinstance(fizzbuzz(15), Iterator) | |
True | |
>>> fizzbuzz(15.0) | |
Traceback (most recent call last): | |
... | |
ValueError: n must be an integer | |
>>> fizzbuzz(-1) | |
Traceback (most recent call last): | |
... | |
ValueError: n must be >= 0 | |
''' | |
if not isinstance(n, int): | |
raise ValueError('n must be an integer') | |
if not n >= 0: | |
raise ValueError('n must be >= 0') | |
numbers = itertools.count(1) | |
fizzes = itertools.cycle((*itertools.repeat('', 3 - 1), 'Fizz')) | |
buzzes = itertools.cycle((*itertools.repeat('', 5 - 1), 'Buzz')) | |
fizzbuzz_generator = (f'{fizz}{buzz}' or n for n, | |
fizz, buzz in zip(numbers, fizzes, buzzes)) | |
return itertools.islice(fizzbuzz_generator, n) | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ python fizzbuzz.py -v | |
Trying: | |
from fizzbuzz import fizzbuzz | |
Expecting nothing | |
ok | |
Trying: | |
[i for i in fizzbuzz(15)] | |
Expecting: | |
[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz'] | |
ok | |
Trying: | |
from collections.abc import Iterator | |
Expecting nothing | |
ok | |
Trying: | |
isinstance(fizzbuzz(15), Iterator) | |
Expecting: | |
True | |
ok | |
Trying: | |
fizzbuzz(15.0) | |
Expecting: | |
Traceback (most recent call last): | |
... | |
ValueError: n must be an integer | |
ok | |
Trying: | |
fizzbuzz(-1) | |
Expecting: | |
Traceback (most recent call last): | |
... | |
ValueError: n must be >= 0 | |
ok | |
1 items had no tests: | |
__main__ | |
1 items passed all tests: | |
6 tests in __main__.fizzbuzz | |
6 tests in 2 items. | |
6 passed and 0 failed. | |
Test passed. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
References