I have a set of float values and I need all the possible permutations that, added together, result in a specific number. Furthermore, I need all permutations to contain exactly eight values.
So, for example, I have the following set of values:
[0.5, 0.8, 1, 1.5, 2, 2.5, 3, 5, 7.5, 10, 12.5, 15, 17.5, 20, 25, 30]
I need to get all the permutations of 8 elements that add up to 20.
A code that works is the following:
N = [0.5, 0.8, 1, 1.5, 2, 2.5, 3, 5, 7.5, 10, 12.5, 15, 17.5, 20, 25, 30]
target = 20
accum = 0
for i1 in N:
accum += i1
for i2 in N:
accum += i2
for i3 in N:
accum += i3
for i4 in N:
accum += i4
for i5 in N:
accum += i5
for i6 in N:
accum += i6
for i7 in N:
accum += i7
for i8 in N:
accum += i8
if accum > target:
accum -= i8
break
elif accum == target:
print(i1, i2, i3, i4, i5, i6, i7, i8)
accum -= i8
break
accum -= i8
accum -= i7
accum -= i6
accum -= i5
accum -= i4
accum -= i3
accum -= i2
accum -= i1
And some of the results are given like this:
0.5 0.5 0.5 0.5 0.5 0.5 2 15 0.5 0.5 0.5 0.5 0.5 0.5 15 2 0.5 0.5 0.5 0.5 0.5 1.5 1 15 0.5 0.5 0.5 0.5 0.5 1.5 15 1 0.5 0.5 0.5 0.5 0.5 2 0.5 15 0.5 0.5 0.5 0.5 0.5 2 3 12.5 0.5 0.5 0.5 0.5 0.5 2 12.5 3 0.5 0.5 0.5 0.5 0.5 2 15 0.5 0.5 0.5 0.5 0.5 0.5 2.5 2.5 12.5 0.5 0.5 0.5 0.5 0.5 2.5 5 10 0.5 0.5 0.5 0.5 0.5 2.5 7.5 7.5 0.5 0.5 0.5 0.5 0.5 2.5 10 5 0.5 0.5 0.5 0.5 0.5 2.5 12.5 2.5 0.5 0.5 0.5 0.5 0.5 3 2 12.5
I can filter the results later with excel. I don't need the code to be sophisticated, I just need the final set of results. As one can see, this code is extremely inefficient, as it takes a lot of time to process, and also gives a great amount of duplicate values. I don't have deep programming knowledge but I know recursive methods are far more efficient. How can I get the results I need?