You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python栈移除盘子函数异常:移除数量判断错误排查

栈移除盘子函数的错误分析

需求说明

需要实现一个从栈顶部移除指定数量盘子的Python函数,规则如下:

  • 移除数量必须是正整数,若≤0则拒绝操作并警告
  • 若移除数量超过栈内盘子总数,同样拒绝操作并警告
  • 校验通过后移除对应数量的盘子,并打印成功信息

用户代码

def remove_plates():
    print(" ")
    print("Remove plates") 
    print("=========")   
    size = read_int("How many plates would you like removed?: ")
    for index, size in enumerate(plates):

        if size <= (index + 1):
            plates.remove(size)
            print(f"{size} removed, success!")
        elif size <= 0:
            print(f"Error: {size} plates cannot be removed from the stack.")
        elif size >= (index + 1):
            print(f"Error: {size} plates cannot be removed from the stack.")
        else:
            print(f"{size} removed, success!")

        print(" ")

测试异常

当plates = [10,8],尝试移除4个盘子时,预期输出Error: 4 plates cannot be removed from the stack.,但实际输出:

Error: 10 plates cannot be removed from the stack.
 
Error: 8 plates cannot be removed from the stack.

错误点分析

  • 变量名被覆盖:函数开头读取的用户输入(要移除的数量)存在size变量里,但后续for index, size in enumerate(plates)把size重新赋值为列表中每个盘子的数值,完全丢失了用户输入的移除数量,这是导致输出异常的核心原因——代码实际在判断每个盘子的数值,而非用户要移除的数量。
  • 逻辑顺序彻底颠倒:正确流程应该是先做前置校验(检查移除数量是否合法、是否超过栈长度),再执行移除操作。现在代码直接遍历盘子列表,把校验和移除混在一起,逻辑完全混乱。
  • 移除操作错误:plates.remove(size)是移除列表中第一个匹配size的元素,不符合栈“从顶部移除”的规则(栈顶对应列表末尾,应该用pop());同时在遍历列表时修改列表,还会导致遍历异常。
  • 条件判断毫无依据:现有if size <= (index +1)等条件完全不符合需求,index+1只是当前遍历的位置序号,和要移除的数量、栈的总长度没有任何关联,判断逻辑完全错误。

修正后的示例代码

def remove_plates():
    print("\nRemove plates") 
    print("=========")   
    # 假设read_int是已实现的读取整数的工具函数
    remove_count = read_int("How many plates would you like removed?: ")
    
    # 第一步:校验移除数量合法性
    if remove_count <= 0:
        print(f"Error: {remove_count} plates cannot be removed from the stack.")
        return
    # 第二步:校验移除数量是否超过栈容量
    if remove_count > len(plates):
        print(f"Error: {remove_count} plates cannot be removed from the stack.")
        return
    
    # 从栈顶(列表末尾)移除指定数量的盘子
    for _ in range(remove_count):
        plates.pop()
    print(f"{remove_count} plates removed, success!")

内容的提问来源于stack exchange,提问作者femalegoat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 01:17:54