Related Tags

python

# Combinations and permutations in Python

Anusheh Zohair Mustafeez

Combinations and permutations are different ways in which a group of objects can be selected and arranged into smaller subgroups. They have far-reaching, real-world applications, especially in programmatic problem-solving.

Python’s itertools package provides simple functionality to compute combinations and permutations.

$C(n,r) = \frac{n!}{r!(n-r)!}$

$P(n,r) = \frac{n!}{(n-r)!}$

## Combinations

The combinations method in itertools takes in a list of values, alongside an integer r, inputs, and then returns a list of all possible combinations in the form of tuples.

### Combinations with replacement

The combinations_with_replacement method works more or less the same as the simple combinations method, but it allows values to be combined with themselves. The following code snippet shows how these methods work:

import itertools

vals = [16, 12, 24, 73, 2, 24]

comb = itertools.combinations(vals, 3)

comb_with_rep = itertools.combinations_with_replacement(vals, 3)

print("Combinations without replacement:")
for val in comb:
print(*val)

print("Combinations with replacement:")
for val in comb_with_rep:
print(*val)

## Permutations

The itertools package provides a similar functionality to compute permutations. The permutations method takes a list as input and an optional integer (r) that defines the length of the desired permutations. The code below shows how permutations can be computed in Python:

import itertools

vals = [16, 12, 24, 73]

perm = itertools.permutations(vals)

perm_r = itertools.permutations(vals, 2)

print("Permutations of length 4:") # Same length as list vals
for val in perm:
print(*val)

print("Permutations of length 2:")
for val in perm_r:
print(*val)

RELATED TAGS

python

CONTRIBUTOR

Anusheh Zohair Mustafeez
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time