1

Problem:

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 code:

def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    for x in nums:
        for y in nums: 
            if nums.index(x) != nums.index(y) and x + y == target :
                    return [nums.index(x), nums.index(y)]

 print (twoSum ([3, 3],6))

Output:

null

In my mind the first "iteration" (I am not quite sure if this is the right term) looks like :

If 0 != 0 (False) and 3 + 3= 6 (True)  --> as  the first condition is not met, the y loops

So the next iteration looks like:

If 0 != 1 (True) and 3 + 3 = 6 (True) 

--> as above conditions are met, the function would return [0,1], but instead the code actually returns null and I do not understand the reason.

So, I would really appreciate, if someone could either explain what's happening, or tell me some keywords, in order to search for the answer on my own :)

3 Answers 3

2

As MoxieBall pointed out, your code returns None because .index() returns the index of the first matching value.

You can use enumerate() to get the true index location:

for x_index, x_value in enumerate(nums):
    for y_index, y_value in enumerate(nums):
        if x_index != y_index and x_value + y_value == target:
            return [x_index, y_index]
Sign up to request clarification or add additional context in comments.

Comments

0

The index method will find the index of the first occurrence in the list. Since your list has the same number twice, no call to index in your code as written will ever return anything except 0. Thus, if nums.index(x) != nums.index(y) is never True so your function returns None.

Comments

0

I think since both the elements in [3,3] are same, hence nums.index(x) and nums.index(y) always give 0 which is equal hence the if-block never execute.

def twoSum(self, nums, target):
  for x in range(len(nums)):
    for y in range(len(nums)): 
        if x != y and nums[x] + nums[y] == target :
                return [x, y]
print (twoSum ([3, 3],6))

this is my solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.