Python - 使用递归查找嵌套列表中的最大值和最小值之和

标签 python recursion

这是我到目前为止得到的一切... 我不知道我做错了什么

首先是我的辅助函数

def max_min(l):

    if isinstance (l[0], list):
        result = max_min(l[0])

    elif len(l) == 2:
        if l[0] < l[1]:
            result = l[0], l[1]
        else:
            result = l[1], l[0]

    else:
        Min, Max = max_min(l[1:])
        if l[0] <= Min:
            result = l[0], Max
        elif l[0] >= Max:
            result = Min, l[0]
        else:
            result = Min, Max

    return result

当尝试这样做时

l = [6, 3, 7, 5, 5, 2, [3, 2], 1]
print max_min(l)

它给了我 (2, 7) 我希望是 (1, 7)

我没主意了……谁能给我指明方向?

最佳答案

当您的程序到达嵌套列表时,它会停止计算其他元素。 block if isinstance (l[0], list) 确保如果存在嵌套列表,则不会评估剩余元素,因为 Min, Max = max_min(l[1:]) 永远不会被调用。

你可以用这样的东西修复 if block :

if isinstance (l[0], list):
    Nested_Min, Nested_Max = max_min(l[0])
    Remainder_Min, Remainder_Max = max_min(l[1:])
    Min = Nested_Min if Nested_Min < Remainder_Min else Remainder_Min
    Max = Nested_Max if Nested_Max > Remainder_Max else Remainder_Max
    result = Min, Max

您还应该将 if len(l) == 2 的检查替换为:

if len(l) == 1:
    result = l[0], l[0]

这样你的函数就不会因为单元素列表而失败。最后,在开头添加如下内容:

if not l:
    return ()

关于Python - 使用递归查找嵌套列表中的最大值和最小值之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35607110/

相关文章:

java - 在递归函数中使用 Scanner 类

python - 运行 ChromeDriver 的多个实例

python - pip安装tornado在VS2017中失败

python - 如何计算椭圆高斯分布的角度

ruby - 当我传入数组时,为什么我的串联会困惑?

java - 作业任务——通过int方法回溯

c++ - 如何解决 requires 子句不兼容

python - 有条件地重命名多个列名称

python - 删除节点lxml python

recursion - F# 递归行为