Skip to content

Instantly share code, notes, and snippets.

@1021ky
Last active October 9, 2023 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1021ky/d0b8a80b621d941f6a48f3d193382252 to your computer and use it in GitHub Desktop.
Save 1021ky/d0b8a80b621d941f6a48f3d193382252 to your computer and use it in GitHub Desktop.
fizzbuzz.py
"""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