I have already found the question to get all possible combinations given a list, but not how to get as well all possible orders. Additionally, I am looking also for another way to output the combinations.
For example, let's say I have following list of elements:
['A', 'B', 'C']
I would like to generate a dictionary matching these 2 ways the combinations can be expressed.
The 1st one is through lists of variable length to express the different combinations and different orders:
[]
['A']
['A','B']
['B','A']
...
['A','B','C']
['A','C','B']
['C','A','B']
...
The 2nd is using fixed-size lists where positive integers indicate in reverse order the position of said element (first element starts at 0, then second element is 1, third element is 2, and so on...), and replacing 'void' element ('') with -1. This gives:
# Initial list: [ 'A', 'B', 'C']
| | |
v v v
[] -> [ -1 , -1 , -1 ]
['A'] -> [ 0 , -1 , -1 ]
['A','B'] -> [ 0 , 1 , -1 ]
['B','A'] -> [ 1 , 0 , -1 ]
...
['A','B','C'] -> [ 0 , 1 , 2 ]
['A','C','B'] -> [ 0 , 2 , 1 ]
['C','A','B'] -> [ 1 , 2 , 0 ]
...
Solution based on @match 's proposal
data = ['A', 'B', 'C']
result = list(chain.from_iterable([permutations(data, x) for x in range(len(data)+1)]))
numbers = []
for item in result:
new_list = [-1, -1, -1]
for entry in item:
idx = data.index(entry)
new_list[idx] = item.index(entry)
numbers.append(new_list)
print(numbers)
[[-1, -1, -1], [0, -1, -1], [-1, 0, -1], [-1, -1, 0], [0, 1, -1], [0, -1, 1], [1, 0, -1], [-1, 0, 1], [1, -1, 0], [-1, 1, 0], [0, 1, 2], [0, 2, 1], [1, 0, 2], [2, 0, 1], [1, 2, 0], [2, 1, 0]]