Last active
October 9, 2023 21:36
-
-
Save 1021ky/d0b8a80b621d941f6a48f3d193382252 to your computer and use it in GitHub Desktop.
fizzbuzz.py
This file contains 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
"""fizzbuzz | |
https://gist.github.com/kazuho/3300555 のようにPythonでif文を使わずにFizzBuzzを実装したもの | |
doctest実行するときは`python -m doctest fizzbuzz.py -v` | |
""" | |
from itertools import cycle | |
from collections.abc import Iterator | |
fizz = cycle(["", "", "Fizz"]) | |
buzz = cycle(["", "", "", "", "Buzz"]) | |
def fizzbuzz(n) -> Iterator[str]: | |
"""関数が呼び出された回数に応じてfizzbuzzとなる文字列を返す | |
:return: fizzbuzzを実現する文字列 | |
>>> fb = fizzbuzz(5) | |
>>> next(fb) | |
'1' | |
>>> next(fb) | |
'2' | |
>>> next(fb) | |
'Fizz' | |
>>> next(fb) | |
'4' | |
>>> next(fb) | |
'Buzz' | |
""" | |
for i in range(1, n + 1): | |
res = (next(fizz) + next(buzz)) or str(i) | |
yield res | |
if __name__ == "__main__": | |
for i in fizzbuzz(100): | |
print(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment