412. Fizz Buzz

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]

Solution 1: Boring

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        
        result = []
        
        for i in range(1, n + 1):
            if i % 3 == 0 and i % 5 == 0:
                result.append("FizzBuzz")
            elif i % 3 == 0:
                result.append("Fizz")
            elif i % 5 == 0:
                result.append("Buzz")
            else:
                result.append(str(i))
                
        return result

Blah. Basic fizzbuzz. No flair. Nothing special.

Solution 2: Spicy and Pythonic

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        
        return ["Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) or str(i) for i in range(1, n + 1)]

Everything about this is pythonic and beautiful. Returning the whole solution in one big list comprehension? Check ✅. Multiplying strings by the ouput of boolean expressions? Check ✅. Having one line of code that’s 100 characters long? Check ✅.

I would maybe not solve it this way in an interview.

Notes

Fizzbuzz is a decently popular programming question. People use it because it’s pretty easy to understand, and it weeds out people who don’t actually know how to program.

Try it on Leetcode