python - Python 在 O(1) 解决方案中引发算术错误
问题描述
我正在研究有关代码信号的越来越多的Plant 问题。问题很简单。我要测量植物达到给定的所需高度需要多少天。植物从种子开始,即 0。我必须考虑到它有一个上升速度和一个下降速度。它非常直截了当,所以我决定使用 while 循环。
以下是问题描述:
Caring for a plant can be hard work, but since you tend to it regularly, you have a plant that grows consistently. Each day, its height increases by a fixed amount represented by the integer upSpeed. But due to lack of sunlight, the plant decreases in height every night, by an amount represented by downSpeed.
Since you grew the plant from a seed, it started at height 0 initially. Given an integer desiredHeight, your task is to find how many days it'll take for the plant to reach this height.
Example
For upSpeed = 100, downSpeed = 10, and desiredHeight = 910, the output should be
growingPlant(upSpeed, downSpeed, desiredHeight) = 10.
# Day Night
1 100 90
2 190 180
3 280 270
4 370 360
5 460 450
6 550 540
7 640 630
8 730 720
9 820 810
10 910 900
The plant first reaches a height of 910 on day 10.
以下是我的尝试:
def growingPlant(upSpeed, downSpeed, desiredHeight):
days = 0
height = 0
while height < desiredHeight :
height += (upSpeed - downSpeed)
days += 1
print(height)
return days-1
但是,由于某种原因,这似乎不起作用。例如,它错误地计算了以下测试用例的天数:
upSpeed: 6
downSpeed: 5
desiredHeight: 10
Output: 9
Expected Output: 5
Console Output:
1
2
3
4
5
6
7
8
9
10
解决方案
想的更简单。
你应该期望Height - upSpeed
def growingPlant(upSpeed, downSpeed, desiredHeight):
days = 0
height = 0
while height < desiredHeight - upSpeed :
height += (upSpeed - downSpeed)
days += 1
print(height)
return days+1
因为在夜幕降临之前,它会达到所需的高度。所以你应该写 while 循环直到desiredHeight - upSpeed。
更简单的是你应该用它来划分。像这样。
def growingPlant(upSpeed, downSpeed, desiredHeight):
nights = (desiredHeight-upSpeed) // (upSpeed - downSpeed) + 1
return nights
推荐阅读
- java - R$layout 被多次定义
- parsing - 从限制性项目中解析 Groovy 脚本(绑定到框架/IDE)
- java - 跨性别的测试用例?
- java - Spring 和 JUnit5 - 如果测试无法启动,请忽略它
- ssl - 通用名称中带有通配符的 SSL 证书
- discord.js - 如何使用 discord.js 删除具有 var 名称的频道
- powerbi - 获取最近 2 个月内没有销售的客户 (ID) 的数量和列表
- python - 当我插入新数据时,是否需要在 NodeJS 中刷新我的 Sqlite3 数据库?
- assembly - MIPS:接受用户输入值并使用循环计算指数的程序
- python - Pyspark - 用空条件替换值