Last active
December 22, 2015 19:19
-
-
Save winny-/6518898 to your computer and use it in GitHub Desktop.
Fizz Buzz iterator python class and equivalent generator function.
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
# This file is in the public domain. | |
class FizzBuzz(object): | |
def __init__(self, low, high=None): | |
if high is None: | |
self.high = low | |
self.current = 1 | |
else: | |
self.high = high | |
self.current = max(low, 1) | |
def __iter__(self): | |
return self | |
def next(self): | |
if self.current > self.high: | |
raise StopIteration | |
else: | |
c = self.current | |
self.current += 1 | |
if (c % 5 + c % 3) == 0: | |
return 'FizzBuzz' | |
elif c % 5 == 0: | |
return 'Buzz' | |
elif c % 3 == 0: | |
return 'Fizz' | |
else: | |
return str(c) | |
def fizz_buzz(low, high=None): | |
if high is None: | |
high = low | |
cur = 1 | |
else: | |
cur = max(low, 1) | |
while cur <= high: | |
c = cur | |
cur += 1 | |
if (c % 5 + c % 3) == 0: | |
yield 'FizzBuzz' | |
elif c % 5 == 0: | |
yield 'Buzz' | |
elif c % 3 == 0: | |
yield 'Fizz' | |
else: | |
yield str(c) | |
def quick_fizz_buzz(low, high=None): | |
if high is None: | |
high = low | |
cur = 1 | |
else: | |
cur = max(low, 1) | |
while cur <= high: | |
c = cur | |
cur += 1 | |
cached_5 = c % 5 | |
cached_3 = c % 3 | |
if (cached_5 + cached_3) == 0: | |
yield 'FizzBuzz' | |
elif cached_5 == 0: | |
yield 'Buzz' | |
elif cached_3 == 0: | |
yield 'Fizz' | |
else: | |
yield str(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment