FizzBuzz ( LeetCode Link )
Why Can't Programmers.. Program? Is the FizzBuzz task an effective way to interview engineers? FizzBuzz Still Works DescriptionWrite a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Solution class Solution(object):def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
for i in range(1, n + 1):
if i % 15 == 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
But, if you prefer List Comprehensions
class Solution(object):def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
return ['Fizz' * (i % 3 == 0) + 'Buzz' * (i % 5 == 0) or str(i) for i in range(1, n + 1)]
Bad question for an interview.
_(:з」∠)_