pythonfizzbuzz

Fizzbuzz for numbers 1 to n without using if/else/switch/loops


How can I write Fizzbuzz for numbers 1 to n without using if/else/switch/loops.

Here is the basic functionality of fizzbuzz wi managed to write without if and else:

print((n % 3 == 0) and "fizz" or "", end = "")
print((n % 5 == 0) and "buzz" or "")

How can I make it work with numbers from 1 to n without using loops/if/else/switch/assert and everything similar to those? And also instead of printing nothing when a number is not divisible by either 3 and 5 it should print the number.

Example:

n = 6

1 2 fizz 3 4 buzz 6

Note: Recursion is allowed.


Solution

  • It is a really simple recursion... (also your example output is wrong, 3 and 6 should not be printed):

    def fizzbuzz(n, i=1):
        print((i % 3 == 0) and "fizz" or "", end='')
        print((i % 5 == 0) and "buzz" or "", end='')
        print((i % 3 != 0) and (i % 5 != 0) and i or '', end=' ')
        i < n and fizzbuzz(n, i+1)
    
    
    fizzbuzz(20)
    

    it becomes a little clearer what is going on if you use if-expressions:

    def fizzbuzz(n, i=1):
        print('fizz' if i % 3 == 0 else "", end='')
        print('buzz' if i % 5 == 0 else "", end='')
        print(i if i % 3 != 0 and i % 5 != 0 else '', end=' ')
        i < n and fizzbuzz(n, i+1)
    

    ..and more obtuse if you only use one print statement:

    print('fizzbuzz' if i%15==0 else 'fizz' if i%3==0 else 'buzz' if i%5==0 else i, sep=' ')
    

    ...and then you might as well just put it all on one line...

    def fizzbuzz(n, i=1):
        print('fizzbuzz' if i%15==0 else 'fizz' if i%3==0 else 'buzz' if i%5==0 else i, sep=' ') or i < n and fizzbuzz(n, i+1)
    

    converting it back to not use if-expressions is straight-forward:

    def fizzbuzz(n, i=1):
        print(i%15==0 and 'fizzbuzz' or i%3==0 and 'fizz' or i%5==0 and 'buzz' or i) or i<n and fizzbuzz(n, i+1)