[英]Python - Using Recursion to find the sum of Max and Min in a nested list
Here's everything I got so far... I can't figure what I have done wrong 这是我到目前为止所做的一切......我无法弄清楚我做错了什么
First my helper function 首先是我的助手功能
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
When tried to do this 当试图这样做
l = [6, 3, 7, 5, 5, 2, [3, 2], 1]
print max_min(l)
It gives me (2, 7)
which i expected to be (1, 7)
它给了我
(2, 7)
我期望(1, 7)
I'm out of ideas... anyone can point me out the directions? 我没有想法......任何人都可以指出我的方向吗?
The moment your program reaches a nested list, it stops evaluating the other elements. 程序到达嵌套列表的那一刻,它就会停止评估其他元素。 The block
if isinstance (l[0], list)
ensures that if there is a nested list, the remaining elements are not evaluated since Min, Max = max_min(l[1:])
is never called. if isinstance (l[0], list)
,则块确保如果存在嵌套列表,则不评估其余元素,因为从不调用Min, Max = max_min(l[1:])
。
You can fix the if
block with something like this: 您可以使用以下内容修复
if
块:
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
You should also replace the check for if len(l) == 2
with: 你还应该用以下方法替换
if len(l) == 2
的检查:
if len(l) == 1:
result = l[0], l[0]
That way your function will not fail for single-element lists. 这样,单元素列表的功能不会失败。 Finally, add something like the following at the beginning:
最后,在开头添加如下内容:
if not l:
return ()
Try this instead: 试试这个:
def min_max(l):
if isinstance(l, list):
t = [min_max(v) for v in l]
return min([m[0] for m in t]), max([m[1] for m in t])
else:
return l, l
Sample output: 样本输出:
>>> l = [6, 3, 7, 5, 5, 2, [3, 2], 1]
>>> min_max(l)
(1, 7)
>>>
Note that an empty list or sub-list will cause an error, so you might need to add a check for that if you care about it. 请注意,空列表或子列表会导致错误,因此如果您关心它,可能需要添加一个检查。
To expand on my comment you would still need to use recursion to flatten the list as you have a mix of integers and lists, the code would look as follows: 要扩展我的注释,你仍然需要使用递归来展平列表,因为你有一个整数和列表的混合,代码看起来如下:
def flatten(l):
tmp = []
for i in l:
if isinstance(i, int):
tmp.append(i)
elif isinstance(i, list):
tmp += flatten(i)
else:
raise AttributeError("found unexpected type {t}".format(t=type(i)))
return tmp
Your recursive function can be simplified and improved at the same time. 您的递归函数可以同时简化和改进。 See the following for details:
有关详细信息,请参阅以下
#! /usr/bin/env python3
def main():
array = [6, 3, 7, 5, 5, 2, [3, 2], 1]
print(sum_min_max(array))
def sum_min_max(array):
return (lambda a, b: a + b)(*get_min_max(array))
def get_min_max(array, minimum=+float('inf'), maximum=-float('inf')):
if array:
head, *tail = array
if isinstance(head, (list, tuple)):
minimum, maximum = get_min_max(head, minimum, maximum)
else:
if head < minimum:
minimum = head
if head > maximum:
maximum = head
minimum, maximum = get_min_max(tail, minimum, maximum)
return minimum, maximum
if __name__ == '__main__':
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.