Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Indexing consecutive values that sum to a target value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading