I recently learned about the Feeling of Computing podcast and listened to the latest episode. One of the hosts challenged listeners to “write Fizz Buzz with no booleans, no conditionals, no pattern matching, or other things that are like disguised booleans.”
Here’s my Python solution:
from itertools import cycle
def string_mask(a, b):
return b + a[len(b) :]
def main():
fizz = cycle(["", "", "Fizz"])
buzz = cycle(["", "", "", "", "Buzz"])
numbers = range(1, 101)
for f, b, n in zip(fizz, buzz, numbers):
print(string_mask(str(n), f + b))
main()
This solution is basically three things put together:
Create endless cycling sequences of
"", "", "fizz", "", "", "fizz", "", "", "fizz", ...and the same idea forbuzz.Combine those two sequences with the numbers 1 through 100 using
zip, to get the following sequence:... ("", "", 7) ("", "", 8) ("Fizz", "", 9) ("", "Buzz", 10) ("", "", 11) ("Fizz", "", 12) ("", "", 13) ("", "", 14) ("Fizz", "Buzz", 15) ("", "", 16) ...Convert the number to a string, then “mask” it with any “Fizz”, “Buzz”, or “FizzBuzz” string. For example,
string_mask("3", "Fizz")returns"Fizz", andstring_mask("10015", "Buzz")returns"Buzz5".Because of this, my code breaks once you reach 10,000 because the digits start “leaking out” the end of the string. You’ll start seeing results like
Buzz0andFizz2.
I’m sure there are better ways to do this, but that was my quick solution. How would you solve this problem?