爬坡任务,在python中使用while循环求解

问题描述 投票:0回答:1

我是Python初学者。我陷入了 while 循环问题:

“黑法隆普赫伯特正试图爬上一个碎石坡。他发现最好的方法是冲上斜坡,直到他筋疲力尽,然后停下来喘口气。然而,当他每次停下来时,斜坡就会沉到下面把他带回刚刚爬过的部分斜坡。

编写一个函数

num_rushes(slope_height, rush_height_gain, back_sliding)
,计算赫伯特爬上高度为
slope_height
米的斜坡需要多少次冲刺,假设每次冲刺都会让他获得
rush_height_gain
米,然后在暂停前的暂停期间向后滑退
back_sliding
米。下一个匆忙。最后一次冲刺仍将被计为 1 次冲刺,尽管其持续时间可能比之前的冲刺要短。

除了 while 循环条件之外,您还需要在每次冲刺后检查 Herbert 是否已到达斜坡顶部。当然,如果他不在斜坡顶部,他只会向后滑行!”

我的解决方案是:

def num_rushes(slope_height, rush_height_gain, back_sliding):
    """Calculates the number of rushes needed for Herbert the Heffalump to climb the slope."""
    
    current_height = 0
    rushes = 0

    while current_height < slope_height:        # If not reach the top yet
        current_height = current_height + rush_height_gain   
        rushes += 1                             # Add 1 to the number of rushes
        if current_height >= slope_height:      # If the last rush takes him to the top, 
            rushes += 0                         # then no sliding back
                                           # If not reach the top yet,
        else:
            current_height = current_height + rush_height_gain - back_sliding   # slide back
            rushes += 1

    return rushes

测试用例是:

ans = num_rushes(10, 10, 9)
print(ans)  ==> SHOULD PRINT 1

ans = num_rushes(100, 10, 0)
print(ans)  ==> SHOULD PRINT 10

ans = num_rushes(15, 10, 5)
print(ans)  ==> SHOULD PRINT 2

ans = num_rushes(100, 15, 7) 
print(ans)  ==> SHOULD PRINT 12

我的函数返回前 3 个测试用例的正确输出。 在最后一个测试用例 (100, 15, 7) 中,它打印 9 而不是 12。

任何人都可以发现我的代码逻辑中有问题吗?我已经尝试了几个小时,但对我来说看起来一切都很好。

python while-loop
1个回答
0
投票

问题出在 else 子句中附加的

rushes += 1
内,这会导致每次高峰计数两次。你可以只使用
if current_height < slope_height
而不是整个
if-else
惨败:

def num_rushes(slope_height, rush_height_gain, back_sliding):
    """Calculates the number of rushes needed for Herbert the Heffalump to climb the slope."""
    
    current_height = 0
    rushes = 0

    while current_height < slope_height:        
        current_height = current_height + rush_height_gain    
        rushes += 1                           
        
        # Check if Herbert hasn't reached the top
        # Herbert slides back if not at the top
        if current_height < slope_height:       
            current_height -= back_sliding      

    return rushes

ans = num_rushes(10, 10, 9)
print(ans)  # Should print 1

ans = num_rushes(100, 10, 0)
print(ans)  # Should print 10

ans = num_rushes(15, 10, 5)
print(ans)  # Should print 2

ans = num_rushes(100, 15, 7) 
print(ans)  # Should print 12

输出:

1
10
2
12
© www.soinside.com 2019 - 2024. All rights reserved.