The content for this site available on GitHub. If you want to launch the notebooks interactively click on the binder stamp below. Binder

< Classes in Python | Contents | Logging Errors and Exceptions in Python >

Permutations and Combinations in Python

Purpose: To help you get comfortable with the topics outlined below

Recomended Usage

  • Run each of the cells (Shift+Enter) and edit them as necessary to solidify your understanding
  • Do any of the exercises that are relevant to helping you understand the material

Topics Covered

  • Permutations and Combinations

Workbook Setup

The following magics will reload all modules before executing a new line and help make sure you follow PEP8 code style.

In [1]:
%load_ext autoreload
%autoreload 2

%load_ext pycodestyle_magic
%pycodestyle_on

Permutations and Combinations

Combinations - ways in which you can group things; 𝐶(𝑛,𝑘) is pronounced "𝑛 choose 𝑘"

Permutations - combinations where order matters; (𝑛,𝑘) is pronounced "the number of 𝑘 such permutations of 𝑛"

How many unique ways can you choose two from a bucket of letters: A B C D?

In [37]:
import itertools


list(itertools.permutations('ABCD', 2))
Out[37]:
[('A', 'B'),
 ('A', 'C'),
 ('A', 'D'),
 ('B', 'A'),
 ('B', 'C'),
 ('B', 'D'),
 ('C', 'A'),
 ('C', 'B'),
 ('C', 'D'),
 ('D', 'A'),
 ('D', 'B'),
 ('D', 'C')]

Note: because of the keyword "unique" we see that order matters and therefore we are talking about permutations.

How many unique ways can you create groups of two from 'ABCD'?

In [41]:
list(itertools.combinations('ABCD', 2))  # Combination: order doesn't matter
Out[41]:
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

How many ways can you choose two things from a list of items [0,1,2]

In [42]:
list(itertools.combinations(range(3), 2))
Out[42]:
[(0, 1), (0, 2), (1, 2)]

How many ways can you permute range(2) with groupings of 2?

In [44]:
list(itertools.permutations(range(3), 2))
Out[44]:
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]

Troubleshooting Tips

If you run into issues running any of the code in this notebook, check your version of Python and Jupyter against mine below

import sys
print(sys.version)
3.7.6 (default, Dec 31 2019, 17:12:14) 
[Clang 11.0.0 (clang-1100.0.33.16)]
!jupyter --version
jupyter core     : 4.6.1
jupyter-notebook : 6.0.2
qtconsole        : not installed
ipython          : 7.9.0
ipykernel        : 5.1.3
jupyter client   : 5.3.4
jupyter lab      : 1.2.3
nbconvert        : 5.6.1
ipywidgets       : not installed
nbformat         : 4.4.0
traitlets        : 4.3.3
In [7]:
# import sys
# print(sys.version)
In [6]:
# !jupyter --version


< Classes in Python | Contents | Logging Errors and Exceptions in Python >