< 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.
%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?
import itertools
list(itertools.permutations('ABCD', 2))
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'?
list(itertools.combinations('ABCD', 2)) # Combination: order doesn't matter
How many ways can you choose two things from a list of items [0,1,2]
list(itertools.combinations(range(3), 2))
How many ways can you permute range(2) with groupings of 2?
list(itertools.permutations(range(3), 2))
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
# import sys
# print(sys.version)
# !jupyter --version
< Classes in Python | Contents | Logging Errors and Exceptions in Python >