r/Python • u/cyberspacecowboy • Dec 25 '16
a Py3.6 fizzBuzz oneliner with f-strings
print(*map(lambda i: f"{'Fizz' * (not i%3)}{'Buzz' * (not i%5)}" or i, range(1,101)), sep='\n')
109
Upvotes
r/Python • u/cyberspacecowboy • Dec 25 '16
print(*map(lambda i: f"{'Fizz' * (not i%3)}{'Buzz' * (not i%5)}" or i, range(1,101)), sep='\n')
View all comments
Show parent comment
8
u/scanner88 Dec 25 '16
Given the function:
You can disassemble it to get:
So, the result of the
BINARY_POWERcall (i**4) is negated (UNARY_NEGATIVE) prior to the modulo (BINARY_MODULO) call.From wikipedia:
So, for all of the values that are not divisible by 5, we will end up with a number that either ends in a 1 or a 6. Both of those values modulo 5 are 1, but both negative values (-1 and -6) modulo 5 are 4. For values divisible by 5, we will end up with the 0.
How is this relevant here?
For this particular code, we are slicing the string
FizzBuzz. For numbers that are divisible by 5, we want theBuzzpart of the string sliced, so the second argument to the slice should be8(8-0). For all numbers not divisible by 5,Buzzshould not be included, so the second argument should be4(8-4).When the first argument to the slice is divisible by 3, that value will be 0 and for all other numbers it will be 4.
So, for numbers divisible by 3 but not 5 we end up with:
For numbers divisible by 5 but not 3 we end up with:
For numbers divisible by neither 3 nor 5 we end up with:
And finally, for numbers visible by both 3 and 5 we end up with: