1

Total/Global maximum of a nested list

Problem:
I'm trying to find the total (or global) maximum of a nested list. The goal is to implement a function that returns the maximum value of a nested list of arbitrary depth (number of nested elements) and size (length of the nested elements).

Expected Behavior:

In [1]: nested_max([[1, 2], [[2, 1], [3, 4]]])
Out [1]: 4

I would be very grateful if someone could help me out on this.

ffent
  • 31
  • 2

2 Answers2

0

Not here to do your homework, but will make an exception:

def iter_list_max(alist, _max=None):
    if _max is None:
         _max = float('-inf')
    for el in alist:
         if isinstance(el, list):
             _max = iter_list_max(el, _max)
         else:
             _max = max(el, _max)
    return _max

Note that your list can only contain other lists of integers, check iterables for a better solution

In [70]: myl = [[1, 2], [[2, 1], [3, 4, [[1,2], [56]]]]]

In [71]: iter_list_max(myl)
Out[71]: 56

E.Serra
  • 1,495
  • 11
  • 14
-1

If you can use numpy module you can get away with a one liner:

globalmax = np.array(list).flatten().max
Edo98
  • 433
  • 2
  • 9