Skip to content

Instantly share code, notes, and snippets.

@mportesdev
Last active August 14, 2020 11:17
Show Gist options
  • Save mportesdev/e496e6c477a1bc0a48bd7830ff5fc2da to your computer and use it in GitHub Desktop.
Save mportesdev/e496e6c477a1bc0a48bd7830ff5fc2da to your computer and use it in GitHub Desktop.
FizzBuzz oneliner in Python

FizzBuzz oneliner in Python

>>> fizz_buzz = ['Fizz'*(i % 3 == 0) + 'Buzz'*(i % 5 == 0) or str(i) for i in range(1, 10_001)]

>>> print('\n'.join(fizz_buzz[: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

A quick test

Every third item must be Fizz or FizzBuzz, and every fifth item must be Buzz or FizzBuzz:

>>> EVERY_THIRD = slice(2, None, 3)
>>> EVERY_FIFTH = slice(4, None, 5)

>>> all(item.startswith('Fizz') for item in fizz_buzz[EVERY_THIRD])
True
>>> all(item.endswith('Buzz') for item in fizz_buzz[EVERY_FIFTH])
True

Credit

Original idea by Giles McMullen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment