Item
??小明家很壕,拥有着一栋高楼大厦,高度为h,某天他从楼顶自由落体释放一个弹力球,该球反弹回来的高度比为bounce,小明的母亲坐在高度为window的窗户前化妆(视线刚好平齐),试问,她的视线水平上能看到几次弹力球经过? 注意(违背则返回-1): ??仪表中的浮动参数"h"必须大于 0 ??浮动参数"bounce"必须大于 0 且小于 1 ??浮动参数"window"必须小于h
题目来源:Codewars(6kyu)
题目原文: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.
Example
例1: 如果h = 3m, bounce = 0.66, window = 1.5m; 那么返回 3次
例2: 如果h = 2m, bounce = 1, window = 1.5m; 那么返回 -1
例3: 如果h = 2m, bounce = 0.5, window = 1m; 那么返回 1次
Knowledge
- 数据类型:整数型(int)、浮点数
- 运算符:比较运算符、赋值运算符、逻辑运算符
- 其他:if - else结构、while循环体、逻辑运算符的优先原则
Parsing
- 题目过长,其实内容很简单,先做一个示意图(例1):
- 设定两个参数:看到的次数、反弹的高度;
- 如果结果不返回-1,那么看到的次数初始值为1次,即第一次下落经过母亲的视线;
- 如果结果不返回-1,那么反弹的高度必须大于母亲的实现水平高度,且初始值为反弹的高度比例因子乘以小明所处的高度;
- 深度朝前推演流程,假设多次反弹,其实每一次反弹,且满足高度时,就经过了2次,那么规律找到了,到这里就可以开始写代码了;
- 从官网题目中可以看到例子返回的结果始终是奇数,其实就可以大胆的猜测see_count = 2n-1,n为正整数,沿着这个灵感就可以入手分析了。
Code
def bouncing_ball(h, bounce, window):
see_count, see_h = 1, bounce*h
if h <= window or h <= 0 or bounce >= 1 or bounce <= 0:
see_count = -1
else:
while see_h > window:
see_h *= bounce
see_count += 2
return see_count
|