>我正在尝试以功能方式解决leetcode问题"Two Sum",但是在第11行和第12行遇到错误,指出"NoneType"对象不可迭代。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def allSum(solnSet, nums, target):
if nums == []:
return list(map(list, set(map(lambda x: tuple(x), solnSet))))
elif (int(sum(solnSet)) + int(nums[0])) <= target:
return allSum(solnSet.append(nums[0]), nums[1:], target)
else:
return allSum(solnSet, nums[1:], target)
soln =[]
v = allSum(soln, nums, target)
return v
o = Solution()
print(o.twoSum([1,2,3,4,5], 5))
[1,4]
这一行是麻烦制造者:
solnSet.append(nums[0])
追加到list
不会返回任何内容(因此默认情况下,它返回 None
)。当你的函数对allSum(solnSet.append(nums[0]), nums[1:], target)
执行递归时,你实际上是在None
传递到第一个参数中。
这将在代码运行map(lambda x: tuple(x), solnSet)
或sum(solnSet)
时引发'NoneType' object is not iterable
异常。
要解决此问题,您可以执行以下操作
allSum(solnSet + [nums[0]], nums[1:], target)
(这将创建一个新列表,并且不会修改原始列表)
或
solnSet.append(nums[0])
allSum(solnSet, nums[1:], target)
(但这确实修改了原始版本)。