FizzBuzz Problem using Python

The FizzBuzz problem is a popular coding interview question. Here you need to check if a number is divisible by 3 and 5 and return the output based on some conditions. If you want to know how to solve the FizzBuzz problem, this article is for you. In this article, I will take you through how to solve the FizzBuzz problem using Python.

FizzBuzz Problem

In the FizzBuzz problem, you will be given an integer, and you need to return a string array where:

  1. the numbers that are divisible by 3 will be replaced with the word “Fizz”;
  2. the numbers that are divisible by 5 will be replaced with the word “Buzz”;
  3. and the numbers that are divisible by both 3 and 5 will be replaced by the word “FizzBuzz”;

Below is an example of the input and output of this problem:

  • Input: 3 | Output: [“1”, “2”, “Fizz”]
  • Input: 5 | Output: [“1”, “2”, “Fizz”, “4”, “Buzz”]

Solving the FizzBuzz Problem using Python

I hope you have understood what the FizzBuzz problem means. Now, below is how you can solve this problem using the Python programming language:

def fizzBuzz(n):
    output = []

    for i in range(1, n + 1):
        if (i % 3) == 0 and (i % 5) == 0:
            output.append("FizzBuzz")
        elif i % 3 == 0:
            output.append("Fizz")
        elif i % 5 == 0:
            output.append("Buzz")
        else:
            output.append(str(i))
    return output

print(fizzBuzz(15))
Output: ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']

So this is how you can solve the FizzBuzz problem using Python. If you are looking for a comprehensive course to prepare for coding interviews, you can follow this course from Meta.

Summary

So, in the FizzBuzz problem, you will be given an integer, and you need to return a string array where:

  1. the numbers that are divisible by 3 will be replaced with the word “Fizz”;
  2. the numbers that are divisible by 5 will be replaced with the word “Buzz”;
  3. and the numbers that are divisible by both 3 and 5 will be replaced by the word “FizzBuzz”;

I hope you liked this article on solving the FizzBuzz problem using Python. You can find many more practice questions for coding interviews solved and explained using Python here. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

Data Strategist at Statso. My aim is to decode data science for the real world in the most simple words.

Articles: 1607

Leave a Reply

Discover more from thecleverprogrammer

Subscribe now to keep reading and get access to the full archive.

Continue reading