0

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.

ramailo sathi
  • 357
  • 1
  • 4
  • 22

2 Answers2

1

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])
Darkstarone
  • 4,590
  • 8
  • 37
  • 74
  • why didn't you do `nums_copy = nums` and explicitly converted `nums` to list? – ramailo sathi May 30 '17 at 03:04
  • That's not a copy, that is just a pointer to the original nums. To copy a list you need to take an extra step. See [this](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) question. – Darkstarone May 30 '17 at 03:06
0

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.

Pythonista
  • 11,377
  • 2
  • 31
  • 50