0

我有一个while循环,它返回爬山所需的“匆忙”次数。山的大小是“坡度高度”,上升高度是“rush_height_gain”减去“back_sliding”。

下面的代码适用于:

ans = num_rushes(15, 10, 5)
print(ans)

打印 1

ans = num_rushes(100, 15,7)
print(ans)

打印 2

ans = num_rushes(10, 10, 9)
print(ans)

打印 12

但返回错误的答案

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

应该打印 10,但打印 9

我不确定这是为什么,任何帮助将不胜感激

def num_rushes(slope_height, rush_height_gain, back_sliding):
    current_height = 0
    rushes = 0
    while current_height < slope_height:

        if rush_height_gain == slope_height:
            rushes+=1
            return rushes

        elif current_height < slope_height:

            if current_height == slope_height:
                return rushes

            else:
                a = rush_height_gain - back_sliding
                current_height += a

            if current_height == slope_height:
                return rushes

            elif current_height > slope_height:
                return rushes

            else:
                rushes+=1


    return (rushes)
4

3 回答 3

4

如果我正确理解了这个问题,我认为您正在寻找的是:

def num_rushes(slope_height, rush_height_gain, back_sliding):
    if rush_height_gain < slope_height and rush_height_gain - back_sliding < 1:
        raise Exception("this is not going to work very well")
    current_height = rushes = 0
    while current_height < slope_height:
        rushes += 1
        current_height += rush_height_gain
        if current_height >= slope_height:
            break
        current_height -= back_sliding
    return rushes

在每次上坡“冲刺”之后,您检查一下您是否已到达顶部。如果是这样,你就完成了,如果不是,你滑下来一点,然后再去!正如@perreal 在他对原始帖子的评论中的链接中指出的那样,如果您向下滑动的次数多于向上滑动的次数,并且第一次没有完全起身,那么您就会遇到问题。在这些情况下,您可能希望抛出异常。

于 2013-06-06T01:53:58.930 回答
0

我认为问题在于以下声明:

        if current_height == slope_height:
            return rushes

back_sliding0,然后在第十次迭代中,current_height90100。然后检查返回 true,并9在增加之前返回。

于 2013-06-06T01:55:21.040 回答
0
def num_rushes(slope_height, rush_height_gain, back_sliding):

    current_height = 0
    rushes = 0

    while current_height < slope_height:

        current_height += rush_height_gain
        rushes += 1

        if current_height < slope_height:
            current_height -= back_sliding

    return rushes
于 2013-06-06T02:03:05.883 回答