Problem Statement: Write a function to implement Fizz-Buzz in a range from 1 to N, where N is the parametered value. The output should be a list of strings from 1 to N.
- Multiples of 3 —> ‘Fizz’
- Multiples of 5 —> ‘Buzz’
- Multiples of 3 and 5 —> ‘FizzBuzz’
Constraints
-
Can we assume the inputs are valid?
- No
-
Can we assume this fits memory?
- Yes.
Test Cases
- None —> Exception
- < 1 —> Exception
- 15 —> [ ‘1’, ‘2’, ‘Fizz’, ‘4’, ‘Buzz’, ‘Fizz’, ‘7’, ‘8’, ‘Fizz’, ‘Buzz’, ‘11’, ‘Fizz’, ‘13’, ‘14’, ‘FizzBuzz’ ]
Algorithm
- Iterate from 1 through n
-
Use the modulo operation to determine if the current iteration is divisible by:
- 3 and 5 —> ‘FizzBuzz’
- 3 —> ‘Fizz’
- 5 —> ‘Buzz’
- else —> string of current iteration return the results.
Complexity:
- Time complexity: O(n)
- Space complexity: O(n)
Code
class FizzBuzz(object):
def fizzbuzz(self, number):
if number is None:
raise TypeError
if number < 1:
raise ValueError
res = []
for i in range(1, number+1):
if(i % 3 == 0 and i % 5 == 0):
res.append("FizzBuzz")
elif (i % 3 == 0):
res.append("Fizz")
elif (i % 5 == 0):
res.append("Buzz")
else:
res.append(str(i))
return res
Unit Test
import unittest
from fizzbuzz import FizzBuzz
class TestFizzBuzz(unittest.TestCase):
def fizz_buzz_solution(self):
fizzbuzz = FizzBuzz()
self.assertRaises(TypeError, fizzbuzz.fizzbuzz, None)
self.assertRaises(ValueError, fizzbuzz.fizzbuzz, 0)
expected = [
'1',
'2',
'Fizz',
'4',
'Buzz',
'Fizz',
'7',
'8',
'Fizz',
'Buzz',
'11',
'Fizz',
'13',
'14',
'FizzBuzz'
]
self.assertEqual(fizzbuzz.fizzbuzz(15), expected)
print("Success: test_fizz_buzz")
def main():
test = TestFizzBuzz()
test.fizz_buzz_solution()
if __name__ == "__main__":
main()
Happy Coding!