This is one basic way (quite easy to come up with).
Start easy first. To start, let alpha = ["a", "b", "c", "d"]
. First find all permutations that start with "a"
:
start_a = [["a"]]
two_start_a = [ start_a[0] + [i] for i in alpha ]
to_three_start_a = [ [ j + [i] for i in alpha ] for j in two_start_a ]
three_start_a = []
for i in to_three_start_a:
#cleaned is to exclude list with multiple values
cleaned = [lst for lst in i if len(set(lst)) == len(lst)]
three_start_element += cleaned
to_four_start_a = [ [ j + [i] for i in alpha ] for j in three_start_a ]
four_start_a = []
for i in to_four_start_a:
#cleaned is to exclude list with multiple values
cleaned = [lst for lst in i if len(set(lst)) == len(lst)]
four_start_element += cleaned
Now our four_start_a
consists all permutations that start with "a"
. The automated version is
start_a = [[alpha[0]]]
two_start_a = [ start_a[0] + [i] for i in alpha ]
k_start_element = two_start_element
for k in range(3, len(alpha)+1):
to_k_start_a = [ [ j + [i] for i in alpha ] for j in k_start_element ]
k_start_a = []
for i in to_k_start_a:
#cleaned is to exclude list with multiple values
cleaned = [lst for lst in i if len(set(lst)) == len(lst)]
k_start_element += cleaned
Then the final k_start_a
is all the permutations that start with the first element of alpha
.
Solution
So, for all letters, we can automate as below
all_permutations = []
for element in alpha:
start_element = [[element]]
two_start_element = [ start_element[0] + [i] for i in alpha ]
k_start_element = two_start_element
for k in range(3, len(alpha)+1):
to_k_start_element = [ [ j + [i] for i in alpha ] for j in k_start_element ]
k_start_element = []
for i in to_k_start_element:
#to exclude list with multiple values
cleaned = [lst for lst in i if len(set(lst)) == len(lst)]
k_start_element += cleaned
all_permutations.extend( k_start_element )