Skip to content

Instantly share code, notes, and snippets.

@soupglasses
Last active September 19, 2020 14:22
Show Gist options
  • Save soupglasses/13d81402d5d9e7315d3d0f72d9273843 to your computer and use it in GitHub Desktop.
Save soupglasses/13d81402d5d9e7315d3d0f72d9273843 to your computer and use it in GitHub Desktop.
Fizzbuzz done with dictionary store and list comprehension
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)
@soupglasses
Copy link
Author

soupglasses commented Sep 5, 2020

$ 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment