I'm trying to extend the code below so that it shows me more than two values that make up a selected sum.
For example, given the numbers:
1.5, 5.4, -3.7, 7.4, 9.1, 28.1, 77.88, 39
I want to find out which of these numbers make up the sum, e.g.
129.68
(i.e. the code will read off the values that make up the: -3.7 + 7.4 + 9.1 + 77.88 + 39) = 129.68
The current code shows only two of the values, and though it doesn't always work, I think the problem is in the findPairs formula.
I'm looking for this because I don't really know which values make up the choosen sum. (It's something similar to Excel's solver, but it's very slow when I input a large number of values.)
Here is my code:
from collections import Counter
def findPairs(lst, K):
res = []
count = Counter(lst)
for x in lst:
y = K - x
if (x != y and count[y]) or (x == y and count[y] > 1):
res.append((x, y))
count.subtract((x, y))
return res
# Driver code
lst = [1.5, 5.4, -3.7, 7.4, 9.1, 28.1, 77.88, 39]
K = 6.9
print(findPairs(lst, K))
Result
[(1.5, 5.4)]
>>>