首页 > 解决方案 > 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

标签: pythonmath

解决方案


想的更简单。

你应该期望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

推荐阅读