Answer the question
In order to leave comments, you need to log in
Implementation of Holland's fizzbuzz problem solution. How does the code work?
you need to print numbers from 1 to 100, only if the number is divisible by 3, print the word "fizz", if it is divisible by 5 - "buzz", and if it is divisible by 15, then - "fizzbuzz"
import math
def fizzbuzz(i):
return [str(i), 'fizz', 'buzz', 'fizzbuzz'][3 - math.ceil((i % 3) / 2) * 2 - math.ceil((i % 5) / 4)]
for i in range(1, 101):
print(fizzbuzz(i))
Answer the question
In order to leave comments, you need to log in
Here physicists are confused with bases :)
By design, it works like this:
The number 3 comes in [3 -
math.ceil
((3 % 3) / 2) * 2 - math.ceil((3 % 5) / 4)]
this part math.ceil((3 % 3) / 2) * 2
3 % 3 = 0
0 / 2 = 0
0 * 2 = 0
Then we calculate math.ceil((3 % 5) / 4):
3 % 5 = 3
ceil from 3/4 = 1
Accordingly, we get:
3 - 0 - 1 = 2
And return [str(i), 'fizz', 'buzz', 'fizzbuzz'][2]
Let's say the number 4 comes in:
math.ceil( (4 % 3) / 2) * 2
4 % 3 = 1
1 / 2 = 0.5 => ceil(0.5) = 1
1 * 2 = 2
math.ceil((4 % 5) / 4)
4 % 5 = 4
4 / 4 = 1
3 - 2 - 1 = 0 Returns [str(i), 'fizz', 'buzz',
'
fizzbuzz'][0]
ceil returns an int.
PS: When I was having fun, I decided this way:
fizzbuzz = lambda x: "Fizz Buzz" if x % 5 == 0 and x % 3 == 0 else "Fizz" if x % 3 == 0 else "Buzz" if x % 5 == 0 else x
for i in range(1,101):
fizzbuzz(i)
Works for me without errors.
The meaning of the formula is to get the index of the element within acceptable limits, i.e. without going beyond [0..3].
If in more detail:
It turns out3 - [0..2] - [0..1] = [0..3]
Typical case (didn't find the word)
Ceil the result needs to be cast to an integer
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question