VictorChars96
VictorChars96

Reputation: 63

Two Sum, Pass value from inside to function call?

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")

Upvotes: 0

Views: 204

Answers (3)

smci
smci

Reputation: 33938

The most Pythonic way to implement this is as a list-comprehension, it's just a one-liner!

>>> [(a[i],a[j]) for i in range(0, len(a)-1) for j in range(i+1, len(a)-1) if a[i]+a[j]==target]

[(4, 5), (10, -1)]

(Note that lend itself to doing early termination, but you can just slice [0]'th element.)

As to your code/ functional approach, I'd rewrite it as this (next time please ask for reviews of working code over on CodeReview.SE, rather than here on SO):

def two_sum (a, target):
    for i in range(0, len(a)):
        for j in range( i + 1, len(a)):
            if a[i] + a[j] == target:
                return (a[i], a[j])
    return None

result = two_sum (a, target)

if result:
    print ("the numbers sum to target", result)
else:
    print ("result is not in range")

Comments:

  • since you call your first index i, call the second index j, not x, which makes it unclear whether x is a value or index
  • it's far more Pythonic to return None than return a sentinel value like -1. The caller can then just test the return the value with simply if result:, you don't need any clunky if result != -1 or if result is None
  • renamed twoSum to two_sum to follow Python naming convention (PEP-8) for function names and variables: lower_case_with_underscores
  • note this implementation does early termination. But if you just change return (a[i], a[j]) to yield (a[i], a[j]), that makes it a generator that sequentially returns all(/any) matching tuples. (you'd need to replace the return None with yield StopIteration)
  • similarly totalOfTwo would be called total_of_two or pair_sum
  • but there's no need to declare temporary variables for totalOfTwo,pairsList, just use the expressions directly
  • recommend you learn the right Python terminology, if you're coming from Java. pairsList is not a list, it's a tuple. array is not an array, it's a list. But I'd just call it a.
  • note we only need to run the left index i up to len(a)-1 instead of len(a), since we know we'll need j to index an element on its right.

Upvotes: 0

user15308374
user15308374

Reputation:

You forgot to return the result

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")

Upvotes: 2

ᴓᴓᴓ
ᴓᴓᴓ

Reputation: 1166

I think this is what you're looking for?

You need to add the pairs to the list, and return them if any are found.

Also, personally I would return the empty list rather than -1 if none are found, as they are different data types.

array = [ 3, 4, 5, 9, 10, -1, 6 ]
target = 9
def twoSum (array, target):
    pairsList = []
    for i in range(0, len(array)):
        for x in range( i + 1, len(array)):
            totalOfTwo = array[i] + array[x]
            if (totalOfTwo == target):
                pairsList.append((array[i], array[x]))
    if len(pairsList) == 0:
        return -1
    else:
        return pairsList
result = twoSum (array, target)

if result != -1:
    print ("the intergers numbers meet target", result)
else:
    print ("result is not in range")

Upvotes: 0

Related Questions