2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

怠惰な FizzBuzz を作ってみた (Python 版)

Posted at

はじめに

先日 怠惰な FizzBuzz を作ってみた という、Ruby で FizzBuzz を実装する記事を投稿しました。今回はそれを Python で実装します。

Ruby 版では怠惰さを Enumerator::Lazy で実現しましたが、Python 版では ジェネレータ を利用します。

実装

itertools 万歳 :innocent:

fizzbuzz.py
import itertools


class FizzBuzzRule(object):
  @classmethod
  def say(cls, word):
    return cls(word)

  def __init__(self, word):
    self.word = word

  def for_multiples_of(self, number):
    return itertools.cycle((*itertools.repeat('', number - 1), self.word))


numbers = itertools.count(1)
fizzes = FizzBuzzRule.say('Fizz').for_multiples_of(3)
buzzes = FizzBuzzRule.say('Buzz').for_multiples_of(5)

fizzbuzz_generator = (f'{fizz}{buzz}' or n
                      for n, fizz, buzz
                      in zip(numbers, fizzes, buzzes))


if __name__ == '__main__':
  for word in itertools.islice(fizzbuzz_generator, 30):
    print(word)
$ python fizzbuzz.py
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?