5 Best Ways to Replace Multiples of 3 and 5 with Fizz Buzz in Python

Rate this post

πŸ’‘ Problem Formulation: We need to write a program in Python that iterates through a range of numbers. If a number is a multiple of 3, it should be replaced with “Fizz”, if it’s a multiple of 5, with “Buzz”, and if it’s a multiple of both 3 and 5, with “FizzBuzz”. Given an input range from 1 to 15, the desired output should be 1, 2, “Fizz”, 4, “Buzz”, “Fizz”, 7,8, “Fizz”, “Buzz”, 11, “Fizz”, 13, 14, and “FizzBuzz”.

Method 1: Using Loop and Conditional Statements

This method utilizes a for loop to iterate through a sequence of numbers. It applies conditional statements to check whether a number is a multiple of 3, 5, or both, and replaces it accordingly with “Fizz”, “Buzz”, or “FizzBuzz”. It’s a traditional approach and easy for beginners to understand.

Here’s an example:

for i in range(1, 16):
    output = ''
    if i % 3 == 0:
        output += 'Fizz'
    if i % 5 == 0:
        output += 'Buzz'
    print(output or i)

The output is:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

In this code snippet, the for loop goes through numbers 1 to 15. Thanks to the if statement, each number is checked for divisibility by 3 and 5, and the appropriate words are concatenated to the output string. If the string is empty (no divisibility), the number itself is printed.

Method 2: Using List Comprehensions

List comprehension in Python is an efficient and concise way to create lists. By combining it with conditional logic, we can generate the Fizz Buzz sequence in a single line of code. This approach is more Pythonic and preferred by intermediate programmers for its brevity.

Here’s an example:

fizz_buzz = ['Fizz' * (i % 3 == 0) + 'Buzz' * (i % 5 == 0) or i for i in range(1, 16)]
print(fizz_buzz)

The output is:

['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']

In this snippet, we’re using a list comprehension that evaluates each number i for divisibility by 3 and 5, appending the result “Fizz”, “Buzz”, or “FizzBuzz” to the output list, or the number i itself if neither condition is met.

Method 3: Using Functions

Creating a function to encapsulate the logic for generating “Fizz”, “Buzz”, or “FizzBuzz” can provide more modularity and reusability to the code. This approach improves code readability and allows for better structure, especially in larger programs.

Here’s an example:

def fizz_buzz(number):
    output = 'Fizz' * (number % 3 == 0) + 'Buzz' * (number % 5 == 0)
    return output if output else number

for i in range(1, 16):
    print(fizz_buzz(i))

The output is:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

This function, fizz_buzz(), takes a number as an argument, checks for divisibility by 3 and 5, and returns the corresponding string; it defaults to returning the number itself if neither condition is true. The function is called within a loop.

Method 4: Using Dictionary Mapping

Using a dictionary, we can map the multiples of 3 and 5 to corresponding strings. This method leverages Python’s powerful data structures and can be especially useful when additional mappings are required for other multiples.

Here’s an example:

mapping = {3: 'Fizz', 5: 'Buzz'}
for i in range(1, 16):
    output = ''.join(mapping[key] for key in mapping if i % key == 0)
    print(output or i)

The output is:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

This code utilizes a dictionary to map the multiples to their corresponding strings and iterates through the numbers, using list comprehension and join to construct the output.

Bonus One-Liner Method 5: Ternary Conditional Expression

The Python ternary conditional expression provides a way to compress simple if-else conditions into a single line. This one-liner is not the most readable but boasts conciseness for coding enthusiasts who love compact expressions.

Here’s an example:

print('\n'.join('Fizz' * (i % 3 == 0) + 'Buzz' * (i % 5 == 0) or str(i) for i in range(1, 16)))

The output is:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

This one-liner does everything inside a join() call, iterating over the numbers and applying the logic to get either “Fizz”, “Buzz”, “FizzBuzz”, or the number itself. The result is joined into a newline-separated string.

Summary/Discussion

  • Method 1: Loop and Conditional Statements. Easy to understand. Verbose. Good for beginners.
  • Method 2: List Comprehensions. Compact and Pythonic. May be less readable to beginners.
  • Method 3: Using Functions. Modular and reusable. Good practice for larger codebases.
  • Method 4: Dictionary Mapping. Flexible and powerful. Great when scaling up for more complex mappings.
  • Method 5: One-Liner. Extremely compact. Prioritizes terseness over readability, which can be a downside.