Python List Permutations
Possible Duplicate: How to generate all permutations of a list in Python I am given a list [1,2,3] and the task is to create all the possible permutations of this list. Expected
Solution 1:
itertools.permutations does this for you.
Otherwise, a simple method consist in finding the permutations recursively: you successively select the first element of the output, then ask your function to find all the permutations of the remaining elements.
A slightly different, but similar solution can be found at https://stackoverflow.com/a/104436/42973. It finds all the permutations of the remaining (non-first) elements, and then inserts the first element successively at all the possible locations.
Solution 2:
this is a rudimentary solution... the idea is to use recursion to go through all permutation and reject the non valid permutations.
def perm(list_to_perm,perm_l,items,out):
if len(perm_l) == items:
out +=[perm_l]
else:
for i in list_to_perm:
if i not in perm_l:
perm(list_to_perm,perm_l +[i],items,out)
a = [1,2,3]
out = []
perm(a,[],len(a),out)
print out
output:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Post a Comment for "Python List Permutations"