Fizz Buzz without conditionals or booleans

I recently learned about the Feeling of Computing podcast and listened to the latest episode. One of the hosts challenged the audience to “Write Fizz Buzz with no booleans, no conditionals, no pattern matching or anything else latent boolean,

Here is 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:

  1. Create an endless cycling sequence of "", "", "fizz", "", "", "fizz", "", "", "fizz", ... Same idea for and buzz,

  2. Combine those two sequences with numbers from 1 to 100 zipTo get the following sequence:

    ...
    ("", "", 7)
    ("", "", 8)
    ("Fizz", "", 9)
    ("", "Buzz", 10)
    ("", "", 11)
    ("Fizz", "", 12)
    ("", "", 13)
    ("", "", 14)
    ("Fizz", "Buzz", 15)
    ("", "", 16)
    ...
    
  3. Convert the number to a string, then “mask” it with any of the “fizz”, “buzz” or “fizzbuzz” strings. For example, string_mask("3", "Fizz") Return "Fizz"And string_mask("10015", "Buzz") Return "Buzz5",

    Because of this, my code breaks once it reaches 10,000 as the digits start “leaking” out from the end of the string. You will start seeing results like Buzz0 And Fizz2,

I am Sure There are better ways to do this, but that was my quick solution. How will you solve this problem?



Leave a Comment