Highest and lowest value of nested lists using recursion

无人久伴 提交于 2021-02-16 13:53:46

问题


I want to take in a list with nested lists. Then print the highest value of index 0 or 2 in the list and the lowest value of index 0 or 2, through using recursion.

This is what I got so far:

lst = [1, 5, [7, 10, []]]

def high_low(my_list):
    new_lst = []
    if not my_list:
        print max(new_lst)
        print min(new_lst)
    elif isinstance(my_list[0], int):
        return new_lst.append(my_list[0]) + high_low(my_list[2:])
    elif isinstance(my_list[0], list):
        return new_lst.append(max(my_list[0])) + high_low(my_list[2:])

This is where I get stuck, as I don't know how to get the highest and lowest value from a nested list and then append it to the new empty list. For example this is what I want the output to look like:

>>> print_tree(lst)
10 
1

回答1:


this can be achieved using a similar & classic problem solving (Flatten an irregular list of lists), no need to reinvent the wheel, just use some working method & post-process:

Flatten the list of lists, then take min & max of it.

import collections

def flatten(l):   # function copied from the link above
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el

lst = [1, 5, [7, 10, []]]

new_list = list(flatten(lst))  # create a list cos we'll be iterating twice on it
print(max(new_list))
print(min(new_list))

result

10
1

with one iteration with a manual loop:

min_value = None
max_value = None
for v in flatten(lst):
    if min_value is None or v < min_value:
        min_value = v
    if max_value is None or v > max_value:
        max_value = v

print(min_value)
print(max_value)

the flatten method is nice because it doesn't create temporary list elements so no unneccesary memory allocations.




回答2:


Here's one possibility to write the code with only one pass, no need for external library or python's min/max:

def high_low(list_or_number):
    if isinstance(list_or_number, list):
        current_min = float('inf')
        current_max = float('-inf')
        for x in list_or_number:
            x_max, x_min = high_low(x)
            if x_max > current_max:
                current_max = x_max
            if x_min < current_min:
                current_min = x_min
        return (current_max, current_min)
    else:
        return (list_or_number, list_or_number)

As an example:

>>> high_low([1, 5, [7, 10, [[12, 16], -10]]])
(16, -10)
>>> high_low(3)
(3, 3)
>>> high_low([3,4,5])
(5, 3)



回答3:


You can use the following recursive function that returns the maximum and minimum among the items in the current list and the maximum and minimum of the sublists:

def high_low(l):
    try:
        l.extend(high_low(l.pop()))
    except AttributeError:
        return [l]
    except IndexError:
        return []
    return max(l), min(l)

so that:

lst = [1, 5, [7, 10, []]]
print(high_low(lst))

outputs:

(10, 1)


来源:https://stackoverflow.com/questions/52576825/highest-and-lowest-value-of-nested-lists-using-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!