As an example, I will write a worn-out FizzBuzz in a Pythonic list comprehension. Real one liner.
def fizzbuzz(N):
"""FizzBuzz list comprehension implementation
Example:
>>> print fizzbuzz(10)
[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz']
>>> print fizzbuzz(30)
[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz', 16, 17, 'Fizz', 19, 'Buzz', 'Fizz', 22, 23, 'Fizz', 'Buzz', 26, 'Fizz', 28, 29, 'FizzBuzz']
"""
return [(i%3==0)*'Fizz' + (i%5==0)*'Buzz' or i for i in range(1, N+1)]
point
(i% 3 == 0) *'Fizz'
determines whether to add a string depending on the truth in parentheses.Recommended Posts