Skip to content
Advertisement

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

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement