Sexy One-liner of Python to Solve the FizzBuzz


The FizzBuzz is a famous beginner problem that is often used to start learning a new programming language. Compared to Simple Hello World, the FizzBuzz requires the usage of Loop and If check. The usual text-book solution to FizzBuzz is (in Python) as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def solve(self, n):
        ans = []
        for i in range(1, n + 1):
            if i % 3 == i % 5 == 0:
                ans.append("FizzBuzz")
            elif i % 3 == 0:
                ans.append("Fizz")
            elif i % 5 == 0:
                ans.append("Buzz")
            else:
                ans.append(str(i))
        return ans
class Solution:
    def solve(self, n):
        ans = []
        for i in range(1, n + 1):
            if i % 3 == i % 5 == 0:
                ans.append("FizzBuzz")
            elif i % 3 == 0:
                ans.append("Fizz")
            elif i % 5 == 0:
                ans.append("Buzz")
            else:
                ans.append(str(i))
        return ans

This isn’t Pythonic at all, with Python, you can do this in one-liner using the list comprehension:

1
2
3
4
class Solution:
    def solve(self, n):
        return ["Fizz" * (i % 3 == 0) + 
                "Buzz" * (i % 5 == 0) or str(i) for i in range(1, n + 1)]
class Solution:
    def solve(self, n):
        return ["Fizz" * (i % 3 == 0) + 
                "Buzz" * (i % 5 == 0) or str(i) for i in range(1, n + 1)]

Here you can use the multiply operator to repeat a string pattern n times in Python. This well serves the purpose of concatenating the Fizz and Buzz when it is mod by both 3 and 5 (which is 15).

The OR operator defines the other cases when the number is not a multiple of 3, 5 or 15.

FizzBuzz:

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
371 words
Last Post: Algorithms to Compute the Fibonacci String Sequence
Next Post: C++ Implementation of Segment Tree

The Permanent URL is: Sexy One-liner of Python to Solve the FizzBuzz

Leave a Reply