初见Python解题之道(九)

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

  1. 数据类型:整数型(int)、浮点数
  2. 运算符:比较运算符、赋值运算符、逻辑运算符
  3. 其他:if - else结构、while循环体、逻辑运算符的优先原则

Parsing

  1. 题目过长,其实内容很简单,先做一个示意图(例1):
    在这里插入图片描述
  2. 设定两个参数:看到的次数、反弹的高度;
  3. 如果结果不返回-1,那么看到的次数初始值为1次,即第一次下落经过母亲的视线;
  4. 如果结果不返回-1,那么反弹的高度必须大于母亲的实现水平高度,且初始值为反弹的高度比例因子乘以小明所处的高度;
  5. 深度朝前推演流程,假设多次反弹,其实每一次反弹,且满足高度时,就经过了2次,那么规律找到了,到这里就可以开始写代码了;
  6. 从官网题目中可以看到例子返回的结果始终是奇数,其实就可以大胆的猜测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:
     # 逻辑运算的优先法则:not > and > or
        see_count = -1
    # 利用while循环 检查 反弹高度是否高于窗户高度
    else:
        while see_h > window:
        	# 更新反弹高度
            see_h *= bounce
            # 每反弹且符合条件一次,则母亲看到两次
            see_count += 2
    return see_count
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

顾平安6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值