1

I'm trying to find the max value of a list or tuple that contains other lists or tuples. My first thought is to flatten it out and then use the max() function to find the maximum from the overall list, but I'm having difficulty doing that. Any suggestions?

An example is you have the tuple: (1, 2, 3, (1, 2)) and the expected output would be 3

Another example is the list [1, (2, 3), [4, 5]] and the output should be 5

This is take two using a flatten function and recalling it:

def flatten(t):
output = []
for item in t:
    if type(item) != type([]) or type(()):
        output.append(item)
    else:
        output.extend(flatten(item))
return output

def max_val(t):
    flatten(t)
    return max(output)
  • 3
    That sounds a perfectly reasonable approach. What difficulties are you having particularly? Have you got some semi-working code someone could help you correct? – Jon Clements Jul 15 '18 at 11:59
  • def a flatten function and recursively call it. – Marcus.Aurelianus Jul 15 '18 at 12:11
  • 3
    Possible duplicate of [Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – bobrobbob Jul 15 '18 at 14:25

3 Answers3

1

You can make custom function to flatten your iterable and the use standard max or min functions:

from collections.abc import Iterable

x = (1, 2, 3, (1, 2))

def my_flatten(iterable):
    for value in iterable:
        if isinstance(value, Iterable):
            yield from my_flatten(value)
        else:
            yield value

print('min = ', min(my_flatten(x)))
print('max = ', max(my_flatten(x)))

Outputs:

min =  1
max =  3
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

You can define a generic function to flatten your inputs using chain.from_iterable and collections.Iterable:

from itertools import chain
from collections import Iterable

x = (1, 2, 3, (1, 2))
y = [1, (2, 3), [4, 5]]

def flatten(x):
    return chain.from_iterable([i] if not isinstance(i, Iterable) else i for i in x)

res = max(flatten(x)) # 3

res = max(flatten(y)) # 5
jpp
  • 159,742
  • 34
  • 281
  • 339
0

You can use the package more_itertools to flatten what you have.

import more_itertools
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
res = list(more_itertools.flatten(lst))

Then you just need to use the max() function.

Liky
  • 1,105
  • 2
  • 11
  • 32