Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Math 152 - Intro to Mathematical Software
2017-02-23
Kiran Kedlaya; University of California, San Diego
adapted from lectures by William Stein, University of Washington
** Lecture 18: Combinatorics (part 1) **
Sage has very well-developed infrastructure for combinatorics, of which we will only scratch the surface here. For PhD-level research in the subject, it is probably the best software available, open-source or otherwise.
Reference: the Sage combinatorics tutorial http://doc.sagemath.org/html/en/reference/combinat/sage/combinat/tutorial.html
To begin with, recall that the number of ways to make an unordered choice of distinguishable objects from among given objects is the binomial coefficient where as usual denotes the factorial function.
You can use the binomial coefficients to count subsets without generating them. However, if you do actually want to generate the list of -element subsets of a given set, you can do that easily!
The Subsets function is an example of a structured set construction. Another important example is the Cartesian product; let's see an example based on playing cards.
Another example is the set of permutations of a list.
Exercise for right now: Use the Permutations function to "shuffle" the deck, i.e., pick a random permutation. (Hint: use the random_element method.)
Another example is the set of partitions of a given nonnegative integer. Let's illustrate with an example:
There is a method for counting partitions without enumerating them.
One can also enumerate partitions where the parts have fixed size, e.g., making change:
... or solving the (original) Chicken McNuggets problem: https://en.wikipedia.org/wiki/Coin_problem
Many combinatorics problems lead naturally to integer sequences. These can be looked up in the On-line Encyclopedia of Integer Sequences (OEIS): http://oeis.org; but better yet, this database is integrated into Sage!
Maybe a less familiar example: let's count set partitions of {1, ..., n}.
Aha, let's read about that first one some more.
Note in passing: many of these constructors are examples of Python iterators, which are effectively implicit tuples: the objects are only produced on demand.
The itertools module provides some useful functionality:
https://docs.python.org/2/library/itertools.html
(Reminder: Sage uses Python 2; some syntax is different in Python 3.)