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.
CodePudding user response:
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
CodePudding user response:
i
and i-1
are already your indices. If you do numbers.index(numbers[i])
, you will just get the index of the first occurrence.
So inside your if statement:
list_values.append(i-1)
list_values.append(i)
Is this what you mean? Not completely clear to me from your description.
Do you want to return all such pairs? Or just the first one you find?
CodePudding user response:
Efficient way to add consecutive numbers in list and return its indices
def two_sum(numbers, target):
return [(ind,ind-1) for ind, (num1, num2) in enumerate(zip(numbers, numbers[1:])) if num1 num2 == target]
print(two_sum([1,2,3,4,1,4], 5))
output:
[(0, 1), (2, 3), (3, 4)] #[(index1, index2)]