# Generate all permutation of a set in Python?

PythonServer Side ProgrammingProgramming

In mathematics, arranging all the members of a set into some order or sequence and if the set is already ordered, rearranging (reordering) its elements is called permutation. We can generate permutation using different technique. Below are some of them,

## Method 1

Python comes with dedicated module for permutations and combinations called itertools.

## First import the module

>>> import itertools
>>>

The permutation function allows us to get permutation of N values within a list, where order matters. For example, selection N = 2 values with [1,2,3,4] is done as follows −

Permutation (order matters):
>>> print(list(itertools.permutations([1,2,3,4],2)))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

## Combination (order does not matter)

>>> print(list(itertools.combinations('1234', 2)))
[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]

## Method 2

Below is the implementation on a list without creating new intermediate lists.

def permute(xs, low=0):
if low + 1 >= len(xs):
yield xs
else:
for p in permute(xs, low + 1):
yield p
for i in range(low + 1, len(xs)):
xs[low], xs[i] = xs[i], xs[low]
for p in permute(xs, low + 1):
yield p
xs[low], xs[i] = xs[i], xs[low]
for p in permute([1, 2, 3]):
print (p)

## output

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]

## Method 3  Using Recursion

import copy
def perm(prefix,rest):
for e in rest:
new_rest=copy.copy(rest)
new_prefix=copy.copy(prefix)
new_prefix.append(e)
new_rest.remove(e)
if len(new_rest) == 0:
print (new_prefix + new_rest)
continue
perm(new_prefix,new_rest)
perm([],[1, 2, 3])

## output

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
Updated on 30-Jul-2019 22:30:26