I would like to write a Python code to be able to obtain some of the possible permutations of a string of characters.
I present two examples to show what I would like to do.
Example 1: Let's say that I have a string of characters that I write
my_list=['1','2','3','4']
What I would like to obtain are the 3 possible permutations starting the pairing from the left, meaning
['1', '2', '3','4'], ['1', '3', '2', '4'], ['1', '4', '2', '3']
So, the first value '1' can be paired with '2' or '3' or '4', and then the remaining pair is '3','4' or '2','4' or '2','3'.
Example 2: Let's say that I have a string of characters that I write
my_list=['1','2','3','4','5','6']
What I would like to obtain are the 15 possible permutations starting the pairing from the left, meaning
['1', '2', '3', '4', '5', '6'],
['1', '2', '3', '5', '4', '6'],
['1', '2', '3', '6', '4', '5'],
['1', '3', '2', '4', '5', '6'],
['1', '3', '2', '5', '4', '6'],
['1', '3', '2', '6', '4', '5'],
['1', '4', '2', '3', '5', '6'],
['1', '4', '2', '5', '3', '6'],
['1', '4', '2', '6', '3', '5'],
['1', '5', '2', '3', '4', '6'],
['1', '5', '2', '4', '3', '6'],
['1', '5', '2', '6', '3', '4'],
['1', '6', '2', '3', '4', '5'],
['1', '6', '2', '4', '3', '5'],
['1', '6', '2', '5', '3', '4']
Where again we have the same kind of pairing as for the first example.
I would also like to obtain the possible permutations of longer strings (8, 10, ...). I would like to use Python because a string of 8 characters leads to 105 possible permutations when starting pairing from the left. Of course, I would like a single code that could give me these permutations for a string of arbitrary length.
The first example is not that difficult but I struggle a lot for the second example. For the first example, I tried using pairs of characters. I define my_list and then another list for the first pair. Then, I remove from my_list the first pair and the resulting string is given by concatenating the first pair and the remaining of my_list. Here is the code for the first example:
my_list_a = ['1', '2', '3', '4']
my_list_b = ['2', '3', '4']
for i in range(1,len(my_list_b)+1):
tmp_list=['2', '3', '4']
c = [my_list_a[0],my_list_a[i]]
tmp_list.remove(my_list_a[i])
print(c+tmp_list)
I tried to adapt this code for the second example but without success so far. I have seen that to deal with permutations we can use itertools but I did not manage to use it for my purpose.
Updated my answer with the correct solution after feedback from the author.