Skip to content

Instantly share code, notes, and snippets.

@konstantinfarrell
Created June 28, 2016 20:42
Show Gist options
  • Save konstantinfarrell/c4f84ea579615da63de0eb325753b71d to your computer and use it in GitHub Desktop.
Save konstantinfarrell/c4f84ea579615da63de0eb325753b71d to your computer and use it in GitHub Desktop.
FizzBuzz one-liner in Python 3
# Using a lambda function
print(list(map(lambda i: "Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i), range(1,101))))
# Using a for loop
for i in range(1, 101): print("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i))
@JonathanDagan
Copy link

list comprehension verion:

[print("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or i) for i in range(101)]

also the:

str(i)

isn't really necessary

otherwise nice implementation

@leoschur
Copy link

Neat!
Didnยดt like the print in the loop though:

FizzBuzzChallenge = "\n".join(["Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i) for i in range(101)])
print(FizzBuzzChallenge)

In this case str(i) is necessary.

@khanfarhan10
Copy link

khanfarhan10 commented Oct 3, 2021

print('\n'.join(list(map(lambda i: "Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i), range(1,int(input())+1)))))

@Dummyapt
Copy link

print(list(map(lambda i: "Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) or str(i), range(0, 101))))

@miron
Copy link

miron commented May 20, 2022

@JonathanDagan really nice! But this one actually works:

_=[print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or i)for i in range(1,101)]

You still get the output, but the print doesn't return the list with None values.

@ijknabla
Copy link

ijknabla commented Mar 9, 2023

i%3==0 โ†’ i%3<1 saves 1 byte per comparison.

[print("Fizz"*(i%3<1)+"Buzz"*(i%5<1)or i)for i in range(1,101)]

@JonathanDagan
Copy link

@ijknabla some next level memory management ๐Ÿ‘Œ๐Ÿ˜‚๐Ÿ‘
would even be 2 bytes since you also changed it for the divisible by 5 or was it already 1 byte for both?

@ijknabla
Copy link

ijknabla commented Apr 6, 2023

@JonathanDagan
YES

  • i%3==0 โ†’ i%3<1 (-1 bytes)
  • i%5==0 โ†’ i%5<1 (-1 bytes)
    total 2 bytes

@JonathanDagan
Copy link

JonathanDagan commented Apr 13, 2023

@ijknabla

๐Ÿ’ฏ

@trslater
Copy link

trslater commented Dec 1, 2023

Similar in length, but using a different technique, and I'm using input and count (itertools), so it goes forever but is user controlled:

[input("fizz"[i%3*4:] + "buzz"[i%5*4:] or i) for i in count(1)]

I guess count shaves off a few more characters as well.

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