Python while循环实现爬坡任务函数逻辑错误排查求助
问题分析与修正
你的代码逻辑在未登顶后的处理环节存在两个关键错误:
- 错误叠加冲刺高度:在else分支中,你写了
current_height = current_height + rush_height_gain - back_sliding,但此时current_height已经在循环开头加过一次冲刺高度,这相当于单次循环内让赫伯特完成了两次冲刺,直接导致高度计算严重偏离实际场景。 - 错误计数冲刺次数:else分支里额外的
rushes +=1完全多余,下滑阶段不属于冲刺动作,只有向上冲刺的动作才算一次次数。
以测试用例num_rushes(100,15,7)为例,你的代码每次未登顶的循环会算2次冲刺,且高度增加15+15-7=23米,这和题目要求的「单次冲刺+下滑仅增加15-7=8米、算1次冲刺」完全不符,这就是返回结果错误的核心原因。
修正后的代码
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: # 执行一次冲刺,计数+1 current_height += rush_height_gain rushes += 1 # 登顶则直接终止循环,无需下滑 if current_height >= slope_height: break # 未登顶才执行下滑,下滑不计数 current_height -= back_sliding return rushes
测试验证
- 针对
num_rushes(100,15,7):前11次冲刺后,每次冲刺+下滑的净高度为8米,第11次冲刺后高度为8*10 +15=95,下滑到88;第12次冲刺后88+15=103≥100,返回12,符合预期。 - 其余三个测试用例也能正常输出正确结果:
num_rushes(10,10,9)→ 1num_rushes(100,10,0)→10num_rushes(15,10,5)→2
内容的提问来源于stack exchange,提问作者Cooper Brian
相关产品推荐
相关产品推荐

