[PYTHON] Permutation generation

Permutation generation

Permutation generation using itertools permutation itertools is an iterator generation module.

test_permutation.py


import itertools
print('permutations(range(4))   : ', list(itertools.permutations(range(4) ) ) )
print('permutations(range(4), 2): ', list(itertools.permutations(range(4), 2 ) ) )

permutations(range(4)) : [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2), (0, 3, 2, 1), (1, 0, 2, 3), (1, 0, 3, 2), (1, 2, 0, 3), (1, 2, 3, 0), (1, 3, 0, 2), (1, 3, 2, 0), (2, 0, 1, 3), (2, 0, 3, 1), (2, 1, 0, 3), (2, 1, 3, 0), (2, 3, 0, 1), (2, 3, 1, 0), (3, 0, 1, 2), (3, 0, 2, 1), (3, 1, 0, 2), (3, 1, 2, 0), (3, 2, 0, 1), (3, 2, 1, 0)] permutations(range(4), 2): [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)]

You can easily generate permutations like this. You can decide the number of the sequence by putting the iterable one in the first argument and the second argument.

Since only the received iterable (list, etc.) position is considered in this permutation generation, it will be duplicated if the same number etc. are included. For example, if you pass [1,2,2], 1,2,2 is only considered as 0,1,2 in .permutations. So it is not considered that the same number will appear. The quickest solution is to eliminate duplication with set (). Note that set () will use a lot of memory when the sequence becomes large.

Recommended Posts

Permutation generation
[python] Permutation generation considering the same elements
Data set generation
#Random string generation
Automatic mosaic generation
[Day 2] Project generation