Last active
September 19, 2020 14:22
-
-
Save soupglasses/13d81402d5d9e7315d3d0f72d9273843 to your computer and use it in GitHub Desktop.
Fizzbuzz done with dictionary store and list comprehension
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_dict = {'Fizz': 3, 'Buzz': 5} | |
def fizzbuzz_gen(num: int) -> str: | |
"""Can easily change the values used at runtime from a dict.""" | |
return ''.join(key * (num % value == 0) for key, value in fizzbuzz_dict.items()) or str(num) | |
def fizzbuzz_str(num: int) -> str: | |
"""About 3x faster than fizzbuzz_gen(), but no flexibility at runtime.""" | |
return "Fizz" * (num % 3 == 0) + "Buzz" * (num % 5 == 0) or str(num) | |
def print_fizzbuzz_to(num: int) -> None: | |
"""Print out results in a human readable way""" | |
print('STR:', ', '.join(fizzbuzz_str(i) for i in range(1, num + 1)) + '.') | |
print('GEN:', ', '.join(fizzbuzz_gen(i) for i in range(1, num + 1)) + '.') | |
if __name__ == '__main__': | |
fizzbuzz_to = int(input('Print fizzbuzz to: ')) | |
print_fizzbuzz_to(fizzbuzz_to) | |
fizzbuzz_dict['Nuzz'] = 7 | |
print("Added 'Nuzz: 7' at runtime.") | |
print_fizzbuzz_to(fizzbuzz_to) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ python fizzbuzz.py Print fizzbuzz to: 15 STR: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz. GEN: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz. Added 'Nuzz: 7' at runtime. STR: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz. GEN: 1, 2, Fizz, 4, Buzz, Fizz, Nuzz, 8, Fizz, Buzz, 11, Fizz, 13, Nuzz, FizzBuzz.