Search code examples
pythonarraysmathpermutationpython-itertools

itertools permutation on oneven amount of variables


I have this formula

x*A + y*B + z*C

x,y,z are variables

A,B,C are constants

I want to apply all possible permutations to that formula and store each result

with a even amount of permutations this is fairly simple

from itertools import permutations 

perm = permutations([1, 2,3])

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]



#  ["1 * A " + 2 * B + 3 * C],   -->append
  #  ["1 * A " + 3 * B + 2 * C],  --->append 
# ............

How to apply this with an uneven permutation array like perm = permutations([1, 2,3,4,5]) ?


Solution

  • itertools.permutations has an optional second argument which lets you choose the size of each permutation:

    perm = permutations([1, 2, 3, 4, 5], r=3)

    Results:

    [(1, 2, 3), (1, 2, 4), (1, 2, 5)...]