0

I want a function that gets multiple nested lists of arrays and returns just one number: the global maximum (or the minimum) of all the numbers appearing within the inputs.

e.g.:

>>> total_max(3.5,[4.5,1,[2,3], np.random.uniform(size=(5,6)),4],[2,-3])
4.5

I don't want multiple numbers as output such in Finding The Largest Number in a Nested List in Python or python max of list of arrays. And I want it to also work with numpy arrays, which is not the case for Total max of a nested list.

Jakob
  • 1,063
  • 9
  • 17
  • 1
    A simple `max(deepflatten(seq))` would do the trick, where any `deepflatten` is any deep-flattening generator. A comparison a few different flattening functions can be found in [this answer](https://stackoverflow.com/a/40813764/11082165). – Brian61354270 Oct 14 '21 at 22:45
  • 1
    Your example does not lend itself to processing by numpy because the dimension sizes are variable (you even have a mix of scalar and vectors in the same dimension). – Alain T. Oct 15 '21 at 02:18
  • @AlainT. In practice I don't use a random numpy array, but numpy arrays that were calulated by other numpy code. In my applications the number of lists and numpy arrays is not very large, but each of the numpy arrays can be quite big. @Brian: Do you think `deepflatten` is also faster than numpy when you have for example only two very big numpy arrays? Flattening everything to a list first could slow down the performance and probably needs more memory? – Jakob Oct 18 '21 at 10:01

1 Answers1

0
import numpy as np

def nested_max(nestedList):
  if not (isinstance(nestedList, list)):
    return np.max(nestedList)
  else:
    return max([nested_max(a) for a in nestedList])

def nested_min(nestedList):
  if not (isinstance(nestedList, list)):
    return np.min(nestedList)
  else:
    return min([nested_min(a) for a in nestedList])

def total_max(*args):
  return max([nested_max(a) for a in args])

def total_min(*args):
  return min([nested_min(a) for a in args])

def total_range(*args):
  return total_min(*args), total_max(*args)

This way one obtains for example:

>>> total_range(3.5,[4.5,1,[2,3], np.random.uniform(size=(5,6)),4],[2,-3])
(-3, 4.5)

This can be used in applications such as https://stackoverflow.com/a/42229589, where one could simply write:

mi, ma = total_range(dfz, xx)

instead of

mi = np.min((dfz.min(), xx.min()))
ma = np.max((dfz.max(), xx.max()))

to find the overall range of a combined plot.

Is there a nicer variant? E.g.: Supporting more types of tuples, sets, array and lists? Shorter code? Computationally more efficient?

Jakob
  • 1,063
  • 9
  • 17