Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Using Recursion to find the sum of Max and Min in a nested list

Here's everything I got so far... I can't figure what I have done wrong

First my helper function

def max_min(l):

    if isinstance (l[0], list):
        result = max_min(l[0])

    elif len(l) == 2:
        if l[0] < l[1]:
            result = l[0], l[1]
        else:
            result = l[1], l[0]

    else:
        Min, Max = max_min(l[1:])
        if l[0] <= Min:
            result = l[0], Max
        elif l[0] >= Max:
            result = Min, l[0]
        else:
            result = Min, Max

    return result

When tried to do this

l = [6, 3, 7, 5, 5, 2, [3, 2], 1]
print max_min(l)

It gives me (2, 7) which i expected to be (1, 7)

I'm out of ideas... anyone can point me out the directions?

like image 732
user984343 Avatar asked Dec 22 '25 04:12

user984343


1 Answers

The moment your program reaches a nested list, it stops evaluating the other elements. The block if isinstance (l[0], list) ensures that if there is a nested list, the remaining elements are not evaluated since Min, Max = max_min(l[1:]) is never called.

You can fix the if block with something like this:

if isinstance (l[0], list):
    Nested_Min, Nested_Max = max_min(l[0])
    Remainder_Min, Remainder_Max = max_min(l[1:])
    Min = Nested_Min if Nested_Min < Remainder_Min else Remainder_Min
    Max = Nested_Max if Nested_Max > Remainder_Max else Remainder_Max
    result = Min, Max

You should also replace the check for if len(l) == 2 with:

if len(l) == 1:
    result = l[0], l[0]

That way your function will not fail for single-element lists. Finally, add something like the following at the beginning:

if not l:
    return ()
like image 96
Mad Physicist Avatar answered Dec 24 '25 00:12

Mad Physicist