The problem I am trying to solve is as follows: Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple / list (depending on your language) like so: (index1, index2).
The faulty solution I have come up with is as follows:
def two_sum(numbers, target):
list_values = []
for i in range(len(numbers)):
if numbers[i-1] + numbers[i] == target:
list_values.append(numbers.index(numbers[i-1]))
list_values.append(numbers.index(numbers[i]))
return list_values
Unfortunately it doesn’t work when the numbers[i-1] == numbers[i]. Rather than returning the two consecutive index values, it will just repeat whichever index value came first (i.e it will give [0,0] rather than [0,1]. I can’t understand why it would do this: as far as I understand, the successive indexing ought not to be affected by the values of the numbers through which I’m iterating. Any help would be much appreciated.
>Solution :
index() will always return the index of first occurrence of the item given. hence numbers[i-1] and numbers[i] returns same index, when both of them are same numbers.
Here in this case, you dont have to search for index anyway, as you already have it as i.
So changing your code like below will help.
def two_sum(numbers, target):
list_values = []
for i in range(len(numbers)):
if numbers[i-1] + numbers[i] == target:
list_values=[i-1,i]
return list_values