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 []
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 []
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 []
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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.