4
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 []

3 Answers 3

4

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 []
Sign up to request clarification or add additional context in comments.

2 Comments

I guess I could go backward because : <not copied>.extend(<copied>) right?
@MaximeRoussin-Bélanger Yep, you should be able to.
3

Instead of list.extend which returns None, you can use list.__iadd__

__iadd__ also extends the list inplace, but returns the list afterward

if you have an aversion to using special methods, you can use iadd from the operator module

from operator import iadd

...

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

4 Comments

That's kind of pointless. Why should we have to call a 'special' method? This issue is more a misunderstanding with the behaviour of the used methods.
@Zizouz212, not really. If you're writing functional style code, you need to know about this, otherwise you'll duplicate code that's already part of the language.
I changed the recursive call to simplier but using your solution : iadd([(aList[0], aList[-1])], compute(aList[1:-1]))
@MaximeRoussin-Bélanger, cool I updated my answer. Now - you still are still making a partial copy with the aList[1: -1]. If you need more performance, you should look at passing extra parameters for the first and last index instead of actually slicing up the list.
1

That's because extend is a function that doesn't return anything, it simply changes the list in-place. A possible solution is to use + instead:

return [(aList[0], lst[len(aList) - 1])] + compute(aList[1:len(aList) - 1])

3 Comments

This causes the first list to be copied each time instead of just extending the existing list
True, but is also the cleanest solution.
Perhaps, but that attitude - when laid layer upon layer upon layer - gives us a lot of the slowness in large programs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.