Python在O(1)解决方案中抛出算术错误

Python在O(1)解决方案中抛出算术错误,python,math,Python,Math,我正在研究代码信号的植物生长问题。问题很简单。我要测量一棵植物达到给定的理想高度需要多少天。植物从种子开始生长,即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 incr

我正在研究代码信号的植物生长问题。问题很简单。我要测量一棵植物达到给定的理想高度需要多少天。植物从种子开始生长,即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

请注意,植物可能在生长一天后达到所需的高度,或在一天内消退后达到所需的高度。你只需检查它在后退后是否达到了所需的高度。

请注意,植物可能在一天的生长后或后退一天后达到所需的高度。你只需检查它在后退后是否达到所需的高度。

植物白天生长,晚上收缩。如果植物在白天达到所需的高度,那么你就完成了


换句话说,你需要在减去下降速度之前加上上升速度并检查高度。

植物白天生长,晚上收缩。如果植物在白天达到所需的高度,那么你就完成了

换言之,在减去下降速度之前,您需要添加上升速度并检查高度。

想得更简单些

你应该期望的高度-提高速度

def生长设备(上升速度、下降速度、所需高度):
天数=0
高度=0
当高度<所需高度-上升速度时:
高度+=(上升速度-下降速度)
天数+=1
打印(高度)
返回天数+1
因为在夜晚来临之前,它将达到所需的高度。 因此,您应该编写while循环,直到desiredHeight-加速

更简单的是,你应该用它来划分。像这样

def生长设备(上升速度、下降速度、所需高度):
夜间=(期望高度上升速度)/(上升速度-下降速度)+1
返回之夜
想得更简单些

你应该期望的高度-提高速度

def生长设备(上升速度、下降速度、所需高度):
天数=0
高度=0
当高度<所需高度-上升速度时:
高度+=(上升速度-下降速度)
天数+=1
打印(高度)
返回天数+1
因为在夜晚来临之前,它将达到所需的高度。 因此,您应该编写while循环,直到desiredHeight-加速

更简单的是,你应该用它来划分。像这样

def生长设备(上升速度、下降速度、所需高度):
夜间=(期望高度上升速度)/(上升速度-下降速度)+1
返回之夜
upSpeed: 6
downSpeed: 5
desiredHeight: 10

Output: 9

Expected Output: 5

Console Output:
1
2
3
4
5
6
7
8
9
10