BitNeBolt
@BitNeBolt

Как решить эту задачу?

Условие
A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.

He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).

His mother looks out of a window 1.5 meters from the ground.

How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?
Three conditions must be met for a valid experiment:

Float parameter "h" in meters must be greater than 0
Float parameter "bounce" must be greater than 0 and less than 1
Float parameter "window" must be less than h.

If all three conditions above are fulfilled, return a positive integer, otherwise return -1.
Note:

The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.


Обычный цикл подходит по правильности подсчета, но занимает слишком много времени. Так как это геометрическая прогрессия, то можно выразить показатель степени знаменателя.

Делаю это следующим кодом:
def bouncingBall(h, bounce, window):
    if (bounce > 0 and window < h and h > 0 and bounce < 1):
        try:
            res = 1 + (2 * int(math.log(window / h, bounce)))
    
        except ZeroDivisionError:
            res = -1
    
        except ValueError:
            res = -1
    
        return res
        
    else:
        return -1


Но вот строчка расчета res, при всех условиях, меня смущает. Не проходят тесты, где результат должен быть равен единице, он получается 3. Если перенести приведение к целому типу в другое место, но не проходят тесты, когда должно быть 3.

В общем. Как исправить строчку подсчета res, и как лучше поступать в аналогичных ситуациях?
  • Вопрос задан
  • 319 просмотров
Решения вопроса 1
@Andy_U
Смотрите на условие:
The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.
Именно тут ваша программа и врет. Когда мячик подлетает точно на уровень окна. У вас результат приведения к int - единица, но это не должно считаться за отсчет. Оно, конечно, авторы задачи не правы, посколько все операции с плавающей точкой по определению не точны...
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы