
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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']
Advertisements