How do I solve a two-sum problem with multiple solutions?

How do I solve a two-sum problem with multiple solutions?

Contents

Problem Description:

So essentially it is a simple two sum problem but there are multiple solutions. At the end I would like to return all pairs that sum up to the target within a given list and then tally the total number of pairs at the end and return that as well. Currently can only seem to return 1 pair of numbers.

So far my solution has to been to try and implement a function that counts the amount of additions done, and while that number is less than the total length of the list the code would continue to iterate. This did not prove effective as it would still not take into account other solutions. Any help would be greatly appreciated

Solution – 1

You can use the itertools module for this job.

``````my_list = [1, 2, 3, 4]
target = 3

out = [x for x in itertools.combinations(my_list, r=2) if sum(x) == target]

print(out)
>>> [(0, 3), (1, 2)]
``````

If you feel like using a python standard library import is cheating, the the official documentation linked above showcases example code for a "low level" python implementation.

Solution – 2

I took your code and did a couple of tweaks to where summations were being tested and how the data was being stored. Following is your tweaked code.

``````def suminlist(mylist,target):
sumlist = []
count = 0
for i in range(len(mylist)):
for x in range(i+1,len(mylist)):
sum = mylist[i] + mylist[x]
if sum == target:
count += 1
worklist = []
worklist.append(mylist[i])
worklist.append(mylist[x])
sumlist.append(worklist)
return count, sumlist

list =  [0, 5, 4, -6, 2, 7, 13, 3, 1]
print(suminlist(list,4))
``````

Things to point out.

• The sumlist variable is defined as a list with no initial values.
• When a summation of two values in the passed list equate to the test value, they are placed into a new interim list and then that list is appended to the sumlist list along with incrementing the count value.
• Once all list combinations are identified, the count value and sumlist are returned to the calling statement.

Following was the test output at the terminal for your list.

``````@Dev:~/Python_Programs/SumList\$ python3 SumList.py
(2, [[0, 4], [3, 1]])
``````

To split the count value out from the list, you might consider splitting the returned data as noted in the following reference Returning Multiple Values.

Give that a try to see if it meets the spirit of your project.

Solution – 3

Issue:

The issue for returning one set of possible several sets remains in the first return line (return sumlist). Based on the code, the function will automatically ends the function as the first set of value that their sum is the same as the target value. Therefore, we need to adjust it.

1. I add a list(finallist[]) at the begining of the function for collecting all the applicable sets that can sum up to the target value. Then, I add a list(list[]) right after the if statement (*since I create an empty list(list[]) right after the if statement, when any sum of two values fulfills the target value, the function will empty the list again to store the new set of two values and append to the finallist[] again). Hence, as long as a set of two numbers can sum up to the target value, we can append them to the list(list[]). Accordingly, I add two more lines of code to append two values into the list(list[]). At the end, I append this list(list[]) to finallist[]. Also, I move the return statement to the final line and adjust the spacing. After this adjustment, the function will not end right after discovering the first possible set of values. Instead, the function will iterate repeatedly until getting all sets of the values and storing in the finalist[].
2. Originally, the function puts the return statement (return -1) at the end of the function for the situation that none of the sets can sum up to the target value. However, after the previous adjustment, the original return statement (return -1) will not have the opportunity to function as everything will end in the previous return line (return finallist). Therefore, I change it to the else part in the if statement (*meaning: when none of the sum of two values adds up to the target value, we will return ‘No two values in the list can add up to the target value.’)

Changes in Function:

``````def suminlist(mylist,target):
# count = 0 # delete
# while count < len(mylist): # delete
for i in range(len(mylist)):
for x in range(i+1,len(mylist)):
sum = mylist[i]+mylist[x]
# count = count + 1 # delete
if sum == target:
# sumlist = mylist[i],mylist[x] # delete
# return sumlist # delete
return 'No two values in the list can add up to the target value.' # add
# return -1 # delete
``````

Final Version:

``````def suminlist(mylist,target):
finallist=[]
for i in range(len(mylist)):
for x in range(i+1,len(mylist)):
sum = mylist[i]+mylist[x]
if sum == target:
list=[]
list.append(mylist[i])
list.append(mylist[x])
finallist.append(list)
else:
return 'No two values in the list can add up to the target value.'
return finallist
``````

Test Code and Output:

``````list =  [0, 5, 4, -6, 2, 7, 13, 3, 1]
print(suminlist(list,100))
# Output: No two values in the list can add up to the target value.
print(suminlist(list,4))
# Output: [[0, 4], [3, 1]]
``````
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.