Home > Software engineering >  how can I get the function to return index of 2 numbers that add up to a target value
how can I get the function to return index of 2 numbers that add up to a target value

Time:02-10

I am writing a function to take a list of integers and an integer called target and return the indices of the two numbers in the list such that they add up to target. But my code doesn't work the way it should. The function ends up not printing anything at all. How can I fix this? I am a beginner and I can't figure out what's wrong :(

def solution(list, target):
    firstindex = 0
    secondindex = -1

    while(firstindex <= len(list)-1):

        if list[firstindex]   list[secondindex] == target:
            print(f"The sum was found at index {firstindex} and {secondindex}")
            break

        else:
            firstindex = firstindex   1
            secondindex = secondindex - 1

#I am calling the function here
solution([1,2,3,4,5, 6], 5)

CodePudding user response:

Not so sure about the approach in general to the task you are trying to solve, depending on the algorithm you implement and the starting parameters you may receive multiple results and not one single value.

Looking at your example list and target value, the pairs (1,4) (2,3) would both solve for the target value.

In principle, in case you're not using any IDE that keeps track of the variable values or don't want to use any library to keep things very lightweight, I'd recommend to use pen and paper and walk through the variable values of your loop or have printouts in the code itself as a simple means to debug, like this:

def solution(list, target): firstindex = 0 secondindex = -1

while(firstindex <= len(list)-1):
    print(firstindex)
    print(secondindex)

    if list[firstindex]   list[secondindex] == target:
        print(f"The sum was found at index {firstindex} and {secondindex}")
        break

    else:
        firstindex = firstindex   1
        secondindex = secondindex - 1

#I am calling the function here solution([1,2,3,4,5, 6], 5)

What you will find is that your second index starting at -1 will decrement simultaneously to the first index, while it does not stay fixed while iterating through the first index. Hope that helps a bit in the debugging. Really, try to solve this question algorithmically on paper first.

Cheers, Let me know how it goes

Edit: I utterly messed up my thinking, as Python does indeed use negative indices for starting with the last item of the list and walking back. Need to stop thinking C...

CodePudding user response:

Don't use list as the variable name for the first list the function is taking, it is a keyword in python.

edit:
you are refering to the keyword list in your function which represents a type object in python. You are basically referring to the classification of the object. Instead assign your variable to another name such as def solution(original, target):

  • Related