gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:03:15 25 4
gpt4 key购买 nike

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

首先是我的辅助函数

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com