Reputation: 650
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 []
Upvotes: 4
Views: 690
Reputation: 304175
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 []
Upvotes: 3
Reputation: 909
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])
Upvotes: 1
Reputation: 4998
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 []
Upvotes: 4