I’ve profiled my application, and it spends 90% of its time in plus_minus_variations.
The function finds ways to make various numbers given a list of numbers using addition and subtraction.
For example:
Input
1, 2
Output
1+2=3
1-2=-1
-1+2=1
-1-2=-3
This is my current code. I think it could be improved a lot in terms of speed.
def plus_minus_variations(nums):
result = dict()
for i, ops in zip(xrange(2 ** len(nums)), \
itertools.product([-1, 1], repeat=len(nums))):
total = sum(map(operator.mul, ops, nums))
result[total] = ops
return result
I’m mainly looking for a different algorithm to approach this with. My current one seems pretty inefficient. However, if you have optimization suggestions about the code itself, I’d be happy to hear those too.
Additional:
- It’s okay if the result is missing some of the answers (or has some extraneous answers) if it finishes a lot faster.
- If there are multiple ways to get a number, any of them are fine.
- For the list sizes I’m using, 99.9% of the ways produce duplicate numbers.
- It’s okay if the result doesn’t have the way that the numbers were produced, if, again, it finishes a lot faster.
This seems to be significantly faster for large random lists, I guess you could further micro-optimize it, but I prefer readability.
I chunk the list into smaller pieces and create variations for it. Since you get a lot less than
2 ** len(chunk)variatons it’s going to be faster. Chunk length is 6, you can play with it to see what’s the optimal chunk length.