[SOLVED] Returning the numbers in a list whose sum is a given target

Issue

input = x[1,2,4,6,3,9]
target = 6

o/p:
the first number is 1 and the second number is 5

I came across this problem and I solved it using this code:

def search(a,b):
    for d in b:
        if a==d:
            m=True
            break
        else:
            m=False
    return m

x=[1,4,5,7,9,6,2]
target=int(raw_input("Enter the number:"))
for i in x:
    if i<target:
        pair=int(target)-int(i)
        in2=search(pair,x)
        if in2==True:
            print "the first number= %d the second number %d"%(i,pair)
            break

How can I do this better or in a more efficient manner?

Solution

My idea is as follows:

x = [1, 4, 5, 7, 9, 6, 2]
target = int(raw_input("Enter the number:"))
for i in xrange(len(x)):
    for ii in xrange(len(x)):
        if (x[i] + x[ii]) == target:
            print "the first number= %d the second number %d" % (x[i], x[ii])

Basically I iterate through the loop twice searching for a case in which the first index + some other index is equal to your target number, then the second index and so on so forth. I hope I was of help. You can add a quit() after the print to quit after the first found match. Best of luck!

Answered By – Damian Chrzanowski

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *