Reputation: 355
The problem statement : Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
My solution(trying to do better than bruteforce approach):
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0,len(nums)):
if (target - nums[i]) in nums.remove(nums[i]): #error
if i != nums.index(target - nums[i]):
return i, nums.index(target - nums[i])
I keep getting Line 9: TypeError: argument of type 'NoneType' is not iterable
.
I believe.remove()
returns a list and I am trying to check if target - nums[i]
is in the list.
Upvotes: 0
Views: 113
Reputation: 11645
a.remove()
doesn't return a list. It returns None
>>> a_list = [1, 2]
>>> print(a_list.remove(1))
None
>>> print(a_list)
>>> [2]
As the error message suggest to iterate an object you need an object which is iterable.
Upvotes: 0
Reputation: 4730
remove()
returns None
. Try this instead:
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0,len(nums)):
nums.remove(nums[i])
if (target - nums[i]) in nums:
if i != nums.index(target - nums[i]):
return i, nums.index(target - nums[i])
Alternately, if you need to maintain nums
, make a copy and remove:
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0,len(nums)):
nums_copy = list(nums)
nums_copy.remove(nums[i])
if (target - nums[i]) in nums_copy:
if i != nums.index(target - nums[i]):
return i, nums.index(target - nums[i])
Upvotes: 1