0

Determining permutations in array which sum to given value and writing to file

I am using permutations from the itertools python module to find combinations of values that sum to zero.

However when I try to write each permutation that satisfies the limit to a text file for further use elsewhere only one value is written and I am unsure why this is the case.

I am quite new to python and eager to learn so feedback and suggestions would be appreciated.

Thanks!

array = [ -0.20, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2 ]

for i in array:

    perm = permutations(array, 3)

for i in sorted(set(perm)):

    if sum(i) == 0:
 
    f = open("charge_array" + ".txt", "w")

    f.write("".join(str(i)))

    f.close()
  • Also, note that rather than generating permutations and removing those who have the same values in different order, you can use `combinations`. – Thierry Lathuille Dec 11 '20 at 21:14
  • Thanks Thierry, I need to use permutations because the order of things matters for my output, but thanks though I guess using combinations would speed things up. – Hamish S Dec 12 '20 at 10:48

0 Answers0