-1

How is possible to populate lists, of fixed length, using all possible permutations of one or all elements of a list?

For instance, I want to populate lists of 3 elements containing all possible permutations of one or all numbers [1,2,3]. All ways of creating lists of length 3, with these 3 numbers, are:

arranging = [[1,1,1], [1,1,2], [1,2,2], [2,2,2], [1,1,3], [1,2,3], [2,2,3], [1,3,3], [2,3,3], [3,3,3]]

To find the possible permutations of each one of this lists I would use:

populating = [set(itertools.permutations(i, 3)) for i in arranging]

Which is equal to:

populating == [{(1, 1, 1)}, {(1, 2, 1), (2, 1, 1), (1, 1, 2)}, {(1, 2, 2), (2, 2, 1), (2, 1, 2)}, {(2, 2, 2)}, {(1, 1, 3), (1, 3, 1), (3, 1, 1)}, {(3, 1, 2), (1, 3, 2), (3, 2, 1), (2, 3, 1), (1, 2, 3), (2, 1, 3)}, {(2, 2, 3), (3, 2, 2), (2, 3, 2)}, {(3, 1, 3), (3, 3, 1), (1, 3, 3)}, {(3, 2, 3), (2, 3, 3), (3, 3, 2)}, {(3, 3, 3)}]

How would you create the list arranging (sorry for the terrible name)? Is there any other better solution?

Rodrigo
  • 137
  • 1
  • 10

1 Answers1

2

You want combinations with replacement:

iter = itertools.combinations_with_replacement([1,2,3], 3)

If you display that as a list you get:

>>> list(iter)
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), 
 (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)]

Note this is not permutations, as it contains (1, 1, 2) but not (1, 2, 1)

TemporalWolf
  • 7,727
  • 1
  • 30
  • 50