Home > Software design >  Python how to return more than one value
Python how to return more than one value

Time:11-15

How do I return more than one possible value? (Two sum problem: Determine if any two number inside an array sum to a number A)

I already figure out how to kind of solve the problem.

def twoSum(arr, A):
    for i in range(len(arr)):
        for j in range(i 1, len(arr)):
            if arr[i]   arr[j] == A:
                return(arr[i], arr[j])
                
print(twoSum([1,2,3,4],5))

However, I only manage to return the first possible value. Although (2, 3) is also correct.

my output: (1, 4)

Is there a way to return multiple values such as

intended output: [(1, 4), (2, 3)]

Thanks in advance.

CodePudding user response:

Technically you return a single value in a form of a tuple, only thing you need to do is to create a collection and add possible value pairs to that one. You can use a list for that like the below:

def twoSum(arr, A):
    sum_values = []
    for i in range(len(arr)):
        for j in range(i   1, len(arr)):
            if arr[i]   arr[j] == A:
                sum_values.append((arr[i], arr[j]))
    return sum_values


print(twoSum([1, 2, 3, 4], 5))

So in this example you have the sum_values variable to collect all possible combinations of sums, and you return value will be the list of these sum pairs.

CodePudding user response:

check numpy library for more dimensional arrays, you can easily solve it

  • Related