0

I have a an element N which can be list or tuple. Element of N can be either an int, a tuple, or a list. The task is to flatten this and return the largest value.

I manage to flatten N and I am able to return a list of integer, however when I apply max() I get an error: TypeError: can only concatenate list (not "int") to list... I am not sure where I get it wrong and why, even when i try to convert the result to list:

def maxVal(n):
    mode = (list,tuple)
    result = sum(([x] if not isinstance(x, mode) else maxVal(x)for x in n), [])
    output = []
    for i in result:
        output.append(i)
    return max(output)

If I use return output (without the max() function) I get: [5, 1, 2, 1, 9]

thanks

2 Answers2

2

Try this code

def max_val(x):
    queue = list(x)
    max_ = float('-inf')
    while queue:
        elem = queue.pop()
        if isinstance(elem, (list, tuple)):
            queue.extend(elem)
            continue
        if elem > max_:
            max_ = elem

    return max_

x = [(1,2,3, [8, 9]), 3, [4,5,6]]

print(max_val(x)) # prints 9
hurlenko
  • 1,363
  • 2
  • 12
  • 17
2

A recursive solution:

>>> def maxVal(elem):
...     if isinstance(elem, (list, tuple)):
...         if len(elem) == 1:
...             return maxVal(elem[0])
...         return max(maxVal(elem[0]), maxVal(elem[1:]))
...     else:
...         return elem
...
>>> maxVal(7)
7
>>> maxVal([9])
9
>>> maxVal([[[11]]])
11
>>> maxVal([[[[11]]], (12, 3), (4,19,(31,2),12), [12, 14, 5]])
31

Code Demo

Booboo
  • 38,656
  • 3
  • 37
  • 60