Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function inside a function, python recursive on a list

def minimizeMaximumPair(lst):
    lst.sort()

    def compute(aList):
        if len(aList) != 0:
            return [(aList[0], lst[len(aList) - 1])].extend(compute(aList[1:len(aList) - 1]))
        return []

    return compute(lst)

When I get the the last recursion step I get an

TypeError: 'NoneType' object is not iterable

I tried returning nothing, and a []

like image 731
Maxime Roussin-Bélanger Avatar asked Feb 09 '23 01:02

Maxime Roussin-Bélanger


1 Answers

The issue is when you call .extend().

Your compute function tries to return the value of .extend(), which is None. Similar to .sort(), .extend() modifies the object itself, rather than returning a modified copy of the object. This is known as mutability. Here's some working code:

def compute(aList):
    if len(aList) != 0:
        out = [(aList[0], lst[len(aList) - 1])]
        out.extend(compute(aList[1:len(aList) - 1]))
        return out
    return []
like image 114
Zizouz212 Avatar answered Feb 12 '23 12:02

Zizouz212