Sexy One-liner of Python to Solve the FizzBuzz
The FizzBuzz is a famous beginner problem that is often used to start learning a new programming language. Compared to Simple Hello World, the FizzBuzz requires the usage of Loop and If check. The usual text-book solution to FizzBuzz is (in Python) as follows:
class Solution:
def solve(self, n):
ans = []
for i in range(1, n + 1):
if i % 3 == i % 5 == 0:
ans.append("FizzBuzz")
elif i % 3 == 0:
ans.append("Fizz")
elif i % 5 == 0:
ans.append("Buzz")
else:
ans.append(str(i))
return ans
This isn't Pythonic at all, with Python, you can do this in one-liner using the list comprehension:
class Solution:
def solve(self, n):
return ["Fizz" * (i % 3 == 0) +
"Buzz" * (i % 5 == 0) or str(i) for i in range(1, n + 1)]
Here you can use the multiply operator to repeat a string pattern n times in Python. This well serves the purpose of concatenating the Fizz and Buzz when it is mod by both 3 and 5 (which is 15).
The OR operator defines the other cases when the number is not a multiple of 3, 5 or 15.
Related: The FizzBuzz Example in Magik Programming Language
--EOF (The Ultimate Computing & Technology Blog) --
Reposted to Algorithms, Blockchain and Cloud
Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com
My contributions
- Steem Blockchain Tools
- Computing & Technology
- Download Youtube Video
- Find Cheap & Bargin VPS: VPS Database
- Online Software and Tools
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
Alternatively, you could proxy to me if you are too lazy to vote! and you can also vote me at the tool I made: https://steemyy.com/witness-voting/?witness=justyy
拍拍拍
This post has been rewarded by #nutbox. Nutbox is the DApp Incubator of Steem , and you can mine PNUT token by staking to us via https://nutbox.io .Contact us at https://discord.gg/zPkMuGY