I tried to pass unique pairs which sum meet the target to the function call. Kind of new with python so let me know how I can fix it.
array = [ 3, 4, 5, 9, 10, -1, 6 ]
target = 9
def twoSum (array, target):
for i in range(0, len(array)):
for x in range( i + 1, len(array)):
totalOfTwo = array[i] + array[x]
if (totalOfTwo == target):
pairsList = (array[i], array[x])
return -1
result = twoSum (array, target)
if result != -1:
print ("the intergers numbers meet target", result)
else:
print ("result is not in range")
You'r code
array = [ 3, 4, 5, 9, 10, -1, 6 ]
target = 9
def twoSum (array, target):
for i in range(0, len(array)):
for x in range( i + 1, len(array)):
totalOfTwo = array[i] + array[x]
if (totalOfTwo == target):
pairsList = (array[i], array[x]) ##### THIS #####
return -1
result = twoSum (array, target)
if result != -1:
print ("the intergers numbers meet target", result)
else:
print ("result is not in range")
My code
array = [ 3, 4, 5, 9, 10, -1, 6 ]
target = 9
def twoSum (array, target):
for i in range(0, len(array)):
for x in range( i + 1, len(array)):
totalOfTwo = array[i] + array[x]
if (totalOfTwo == target):
return (array[i], array[x]) ##### THIS ####
return -1
result = twoSum (array, target)
if result != -1:
print ("the intergers numbers meet target", result)
else:
print ("result is not in range")
But this is only the first result, so...
array = [ 3, 4, 5, 9, 10, -1, 6 ]
target = 9
def twoSum (array, target):
rsts = [] # save rsts hear
for i in range(0, len(array)):
for x in range( i + 1, len(array)):
totalOfTwo = array[i] + array[x]
if (totalOfTwo == target):
rsts.append((array[i], array[x])) # add answer to rsts
return -rsts
result = twoSum (array, target)
if we haven't correct answer result is an empty list ([]
), so
if result != []: # changed -1 with []
print ("the intergers numbers meet target", result)
else:
print ("result is not in range")