snippetpythonModerate
FizzBuzz example in Python for game manual
Viewed 0 times
examplemanualfizzbuzzgameforpython
Problem
I'm developing an implementation of the FizzBuzz game as part of an edutainment game for a retro video game platform. In its manual, I want to mention the history of writing a bot for the FizzBuzz game as a programmer screening test since Jeff Atwood's blog post, including sample answers in a few popular programming languages. But I don't want to confuse readers with poorly written code.
So is there anything unclear or unpythonic about my approach to FizzBuzz?
So is there anything unclear or unpythonic about my approach to FizzBuzz?
# Each of several divisors has a name. For each number,
# print the names of all divisors that divide the number,
# if any. Otherwise print the number itself.
divs = [
(3, "fizz"),
(5, "buzz"),
]
for n in range(1, 101):
# Make a string containing names of divisors of n
ndivs = ''.join(name for (divisor, name) in divs
if n % divisor == 0)
# If the string is empty, print the number instead
print(ndivs or n)Solution
Nicely done! The great thing about this implementation that it's easy to extend (for example if you want to add
Tuples are immutable, as opposed to lists.
Since the list of fizz-buzz-jazz definitions don't change during the run of the program,
the
Tuples are faster than lists.
The parentheses are unnecessary around
This may be a matter of taste,
but I'd find this line more readable on a single line:
(7, "jazz"). I have only some minor nitpicks.Tuples are immutable, as opposed to lists.
Since the list of fizz-buzz-jazz definitions don't change during the run of the program,
the
divs list can be a tuple.Tuples are faster than lists.
divs = (
(3, "fizz"),
(5, "buzz"),
)The parentheses are unnecessary around
(divisor, name):ndivs = ''.join(name for (divisor, name) in divs
if n % divisor == 0)This may be a matter of taste,
but I'd find this line more readable on a single line:
ndivs = ''.join(name for divisor, name in divs if n % divisor == 0)Code Snippets
divs = (
(3, "fizz"),
(5, "buzz"),
)ndivs = ''.join(name for (divisor, name) in divs
if n % divisor == 0)ndivs = ''.join(name for divisor, name in divs if n % divisor == 0)Context
StackExchange Code Review Q#73673, answer score: 10
Revisions (0)
No revisions yet.