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

Python递归调用函数返回None 木料装箱逻辑问题排查

木料装箱递归返回异常问题修复

问题场景

现有记录木料长度(单位:cm)的列表,需按以下规则装入箱子:

  • 每个箱子共4行,每行放置木料的总长度不得超过140cm
  • 单根木料长度超过140cm时,可单独放置在空行中
  • 函数需要返回3项结果:
    1. 木料所在行的索引
    2. 木料在所在行的起始位置
    3. 木料所在箱子的索引

初始编写的代码处理第一个箱子时运行正常,但箱子装满后,在函数内重置箱子并递归调用自身时出现异常,返回结果为None或错误值。

初始错误代码

my_woods = [50, 60, 70, 40, 30, 120, 90, 50, 70, 70, 60, 30, 45, 25, 40, 45, 150, 60, 70, 80, 25, 40, 80]
row_length = 140

box = [[], [], [], []]
box_idx = 1

def addtobox(length, box, box_idx):
    for idx, row in enumerate(box):
        if row == []:
            row.append(length)
            return idx, sum(row) - length, box_idx
        else:
            sum_row = sum(row)
            if row_length - sum(row) >= length:
                row.append(length)
                return idx, sum(row) - length , box_idx
    box = [[], [], [], []]
    box_idx += 1
    addtobox(length, box, box_idx)

for wood in my_woods:
    print(addtobox(wood, box, box_idx))

错误运行结果

(0, 0, 1)
(0, 50, 1)
(1, 0, 1)
(1, 70, 1)
(0, 110, 1)
(2, 0, 1)
(3, 0, 1)
(3, 90, 1) # 最后一个正确结果
None
None
None
(1, 110, 1)
None
None
None
None
None
None
None
None
None
None
None

问题根因

两个核心错误导致返回异常:

  1. 递归调用缺少return关键字:箱子装满后新建箱子递归调用addtobox时,没有把递归的返回值透传到外层,函数无明确返回值时默认返回None
  2. 局部变量状态不同步:函数内新建的box是局部变量,不会修改外层全局的旧箱子对象,下一次调用还是用已经装满的旧箱子做判断,反复触发无效递归

修复后代码

my_woods = [50, 60, 70, 40, 30, 120, 90, 50, 70, 70, 60, 30, 45, 25, 40, 45, 150, 60, 70, 80, 25, 40, 80]
row_length = 140

current_box = [[], [], [], []]
current_box_idx = 1

def addtobox(length):
    global current_box, current_box_idx
    for row_idx, row in enumerate(current_box):
        row_total = sum(row)
        # 空行可放置任意长度木料(包含超过140cm的长料)
        if not row:
            row.append(length)
            return (row_idx, row_total, current_box_idx)
        # 非空行校验剩余空间是否足够
        if row_length - row_total >= length:
            row.append(length)
            return (row_idx, row_total, current_box_idx)
    # 当前箱子装满,初始化新箱子
    current_box = [[], [], [], []]
    current_box_idx += 1
    # 递归时必须return透传计算结果
    return addtobox(length)

for wood in my_woods:
    print(addtobox(wood))

修复说明

  • 移除函数传参的box和box_idx,改用全局变量维护当前装箱状态,避免局部变量赋值不更新外层状态的问题
  • 递归调用前增加return,把新箱子内计算得到的位置结果逐层返回,消除默认None返回问题
  • 空行逻辑天然支持长度超过140cm的木料放置,无需额外分支判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 02:27:23