HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Returns two elements from a list whose sum is a target variable

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
targetwhoseelementstworeturnssumlistfromvariable

Problem

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

Solution

Your search function is terribly unclear. search is a vague name, and a, b, d and m don't communicate anything. Looking at the usage I can see you're testing if a number is in the list, but Python can already do that for you much more readably.

if number in list


The in keyword tests if a value exists in a list, returning either True or False. So you can forget about search and just directly test for pair's existence in the main loop:

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)
        if pair in x:
            print "the first number= %d the second number %d"%(i,pair)
            break


Back to the naming, x is not clear, at least using numbers indicates what it contains. x implies a single value which makes using for i in x extra confusing. pair also sounds like it's multiple items, when really it's the difference you want.

You also don't need to call int on i when the list is populated with integers already.

Lastly, you're using the old form of string formatting. You should instead use str.format, like so:

print("the first number= {} the second number {}".format(i,pair))


It works very similarly, except that it's type agnostic. It will just do it's best to get a string representation of the two values and insert them. There's lots of other uses for this approach so it's good to get used to.

Code Snippets

if number in list
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)
        if pair in x:
            print "the first number= %d the second number %d"%(i,pair)
            break
print("the first number= {} the second number {}".format(i,pair))

Context

StackExchange Code Review Q#111912, answer score: 5

Revisions (0)

No revisions yet.