This is really a follow on from a question I asked earlier this year on Stack Overflow. I received a great answer to the following problem:
I'm trying to code up something simple and pythonic to identify combinations of values from a list which sum to a defined value, within some tolerance.
For example:
if A=[0.4,2,3,1.4,2.6,6.3] and the target value is 5 +/- 0.5, then the output I want is (2,3), (1.4,2.6), (2,2.6), (0.4,2,3), (0.4,3,1.4) etc. if no combinations are found then the function should return 0 or none or something similar.
I implemented the suggestion in my code. However, the method has quickly become the performance limiting step in my code. It's fairly quick to run each iteration but it is being run many, many times.
Can you see any way to optimise this function or replace it with something much faster?
def findSum(self, dataArray, target, tolerance=0.5):
for i in xrange(1, len(dataArray)+1):
results = [list(comb) for comb in list(itertools.combinations(dataArray, i))
if target-tolerance < sum(map(float, comb)) < target+tolerance]
if len(results) != 0:
return results
A = [4,20,30,14,26,63]
and the target range is 45 to 55? How large would your scaled target value be then in your real use case? And how many items can the list have? \$\endgroup\$