V
V
Vladislav Shulkevich2016-05-24 16:25:28
Python
Vladislav Shulkevich, 2016-05-24 16:25:28

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))

This code throws an exception: TypeError: list indices must be integers, not float
That is, what should be calculated in the index of the list, and it should be 0, 1, 2 or 3, is not converted to int. But by design, how does this formula work?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexey Sergeev, 2016-05-24
@vladshulkevich

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)

A
Anton Fedoryan, 2016-05-24
@AnnTHony

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]

#
#algooptimize #bottize, 2016-05-24
@user004

Typical case (didn't find the word)
Ceil the result needs to be cast to an integer

V
Vladislav Shulkevich, 2016-05-24
@vladshulkevich

How to learn to compose such formulas yourself?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question