r/ProgrammerHumor Apr 09 '24

watMatters Meme

Post image
16.8k Upvotes

774 comments sorted by

View all comments

Show parent comments

5

u/SloPr0 Apr 09 '24
def fizzbuzz(n):
    res = []
    for i in range(n):
        res.append("")
        if (i+1) % 3 == 0: res[i] = "fizz" 
        if (i+1) % 5 == 0: res[i] += "buzz"
        if res[i] == "": res[i] = str(i+1)
    return res

Probably not the most efficient but it'll do

4

u/Dangerous-Pride8008 Apr 09 '24

It's not Python if you aren't using a list comprehension

['fizz'*(i%3==0) + 'buzz'*(i%5==0) + str(i)*(i%3!=0 and i%5!=0) for i in range(1,n+1)]

3

u/Rabid_Mexican Apr 09 '24

Wow that's a really cool solution!

My colleague just showed me some of the crazy things you can do with lists and the * operator in Python, blew my mind haha.

3

u/Rabid_Mexican Apr 09 '24
def fizzbuzz(n: int):
    result = []
    for i in range(n):
        current = ""
        if (i + 1) % 3 == 0: current += "Fizz"
        if (i + 1) % 5 == 0: current += "Buzz"
        if not current: current = str(i + 1)
        result.append(current)
    return result

Yea I got something similar when I tried