
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Replace Multiple of 3 and 5 With Fizz, Buzz in Python
Suppose we have a number n. We have to find a string that is representing all numbers from 1 to n, but we have to follow some rules.
When the number is divisible by 3, put Fizz instead of the number
When the number is divisible by 5, put Buzz instead of the number
When the number is divisible by 3 and 5 both, put FizzBuzz instead of the number
To solve this, we will follow these steps −
- For all number from 1 to n,
- if number is divisible by 3 and 5 both, put “FizzBuzz”
- otherwise when number is divisible by 3, put “Fizz”
- otherwise when number is divisible by 5, put “Buzz”
- otherwise write the number as string
Let us see the following implementation to get better understanding −
Example
class Solution(object): def fizzBuzz(self, n): 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 ob1 = Solution() print(ob1.fizzBuzz(15))
Input
15
Output
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
- Related Articles
- Fizz Buzz in Python
- Fizz Buzz Implementation in C++
- Find the largest multiple of 2, 3 and 5 in C++
- String replace multiple characters with an asterisk in JavaScript
- How to replace \ with in Python?
- How to replace multiple spaces with a single space in C#?
- Replace NaN with zero and infinity with large finite numbers in Python
- Search and Replace in Python
- Replace NaN with zero and fill positive infinity values in Python
- Replace NaN with zero and fill negative infinity values in Python
- How can I use MySQL replace() to replace strings in multiple records?
- Write a program in Python to replace all the 0’s with 5 in a given number
- Find and Replace Pattern in Python
- Python Pandas - Mask and replace NaNs with a specific value
- Check if binary string multiple of 3 using DFA in Python

Advertisements