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

Python实现最长连续相同数字序列功能代码运行异常排查

问题分析
  • 函数内部第一行直接执行了lst1 = [],无论传入的参数是什么都会被清空为空列表,后续遍历lst1的循环完全不会执行,最终只会输出初始设置的lmax=-9999和maxi=-9999
  • 输入获取逻辑错误:input()返回的是空格分隔的字符串,没有做拆分和类型转换,就算不清空列表,遍历的也是字符串的单个字符(包括空格),无法正确识别数字
  • 不建议将input()作为函数默认值使用,Python的函数默认值在函数定义阶段就会执行,不会每次调用函数时重新触发输入
修复代码
def lista_egale(lst1):
    l = 0
    maxi = -9999
    prev_one = None
    lmax = -9999
    for current in lst1:
        if prev_one == current:
            l += 1
        else:
            l = 1
        if l > lmax:
            lmax = l
            maxi = current
        prev_one = current
    print("longest sequence is ", lmax, " and ", maxi)

# 输入处理逻辑移到函数外部,拆分字符串并转换为整数列表
input_str = input("numbers go here ")
num_list = list(map(int, input_str.split()))
lista_egale(num_list)

输入测试用例1 2 2 2 2 3 4 5 6 2 2 2即可得到预期输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:00:05