Permutations are the various possible ways that elements in a collection can be arranged. For example if we have a set, {A, B, C}
, the full-length permutations are as follows.
{A, B, C}
{A, C, B}
{B, A, C}
{B, C, A}
{C, B, A}
{C, A, B}
The permutations()
function in itertools
module generates the permutations for a given iterable.
permutations(iterable, r = None)
iterable |
Required. The iterable whose permutations we want. |
r |
Optional. The length of the permutations to be returned. If not given it defaults to the length of the iterable. |
The function returns an iterator of tuples where the tuple contains successive r
-length permutations of the elements of the given iterable. If r is not given only the full length permutations are returned.
from itertools import permutations
data = ["A", "B", "C"]
perms = permutations(data)
for perm in perms:
print(perm)
In the above example, we didn't specify the r
parameter, hence the full-length permutations were returned.
In the following example we us the permuations function with the r parameter given.
from itertools import permutations
data = ["A", "B", "C"]
perms = permutations(data, r = 2)
for perm in perms:
print(perm)
Generate all possible permutations
To generate all possible permutations of a given iterable, we can use a loop such that with each iteration, we specify a higher value for r
until all the permutations are exhausted.
In the following example, we use a for loop to generate all possible permutations for the input iterable.
from itertools import permutations
data = ["A", "B", "C"]
for i in range(len(data) + 1):
print(f"\nlength {i}")
#get the permutations with length i
perms = permutations(data, r = i)
print(*perms, sep = '\n')