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

Python递归函数执行else分支return语句后仍不停止运行问题排查

Python递归计算序列最大涨幅异常问题修复

你的代码核心问题是所有执行递归调用的分支都没有添加return关键字,导致递归计算出的结果无法逐层回传给上层调用,最终外层调用拿到的是空值None,而非预期的计算结果。
具体问题点:

  • 当传入参数不是列表时,你调用了max_increase(list(seq))但没有返回该调用的结果,函数执行完这行后会默认返回None
  • 当最大值位置小于最小值位置时,你调用了切片后的递归逻辑但同样没有返回结果,也会返回空值

修正后完整代码

def max_increase(seq):
    if len(seq) == 0 :
        return 0
    elif not isinstance(seq, list):
        # 新增return返回递归调用结果,isinstance兼容性优于type判断
        return max_increase(list(seq))
    elif seq.index(max(seq)) < seq.index(min(seq)):    
        # 新增return返回递归调用结果
        return max_increase(seq[seq.index(min(seq)):])
    else: 
        return max(seq) - min(seq)
            
btc_data = [ 6729.44, 6690.88, 6526.36, 6359.98, 6475.89, 6258.74,
                 6485.10, 6396.64, 6579.00, 6313.51, 6270.20, 6195.01,
                 6253.67, 6313.90, 6233.10, 6139.99, 6546.45, 6282.50,
                 6718.22, 6941.20, 7030.01, 7017.61, 7414.08, 7533.92,
                 7603.99, 7725.43, 8170.01, 8216.74, 8235.70, 8188.00,
                 7939.00, 8174.06 ]
btc_data.reverse()

# 输出结果保留两位小数即可得到预期值
print(round(max_increase(tuple(btc_data)), 2))

执行上述修正后的代码,输出结果为589.45,和预期一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:27:04