patternpythonMinor
Returns two elements from a list whose sum is a target variable
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)
breakSolution
Your search function is terribly unclear.
The
Back to the naming,
You also don't need to call
Lastly, you're using the old form of string formatting. You should instead use
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.
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 listThe
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)
breakBack 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 listx = [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)
breakprint("the first number= {} the second number {}".format(i,pair))Context
StackExchange Code Review Q#111912, answer score: 5
Revisions (0)
No revisions yet.