DEV Community

QUANON
QUANON

Posted on

Lazy FizzBuzz (Python ver.)

Recently I wrote a post about FizzBuzz with Ruby. Now I want to do that with Python.

In the previous post, I use Enumerator::Lazy for laziness (which means lazy evaluation for list) with Ruby, and I use generator with Python.

import itertools  # what a great tools 😊


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)
Enter fullscreen mode Exit fullscreen mode
$ 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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)