Section 1.3 Combinations
¶The number of ways to choose a \(k\)-set from an \(n\)-set (of distinct objects) is the binomial coefficient
This computation in Sage is straightfoward. We compute \(\binomial{30}{8}\text{.}\)
The results are sensible for unusual inputs.
Note that in static versions of this document we do not show the full traceback when there is an error, since much of it is irrelevant, and will vary from system to system. Always read the last line of the error messages first and work your way upwards if more hints are needed. The quality of error messages varies, and if this bothers you, then improving some of them is a great way to become a Sage Developer. For example the message here would be better if it indicated that the 8.5
was part of the problem, and not the 30
.
The routines for enumerating combinations are entirely similar for those that generate permutations, so if you have not already, read Section 1.2 for more detail and background. We generate some combinations of pets.
Note that mathematically, a combination is a set, while in Sage the objects created are Python lists, which have an order. This is typical in much of Sage and it should not be difficult to translate back and forth. Sage does have a Set
class, but it is important not to confuse it with Python's set
object, since they behave differently.
As with Arrangements
, a Sage object of the class Combinations
is a generator and also is therefore an iterable. Being an iterable means we can write a loop such as
for x in doubles: print x
Being a generator means that doubles
automatically has .next()
and .previous()
methods that will produce the adjacent items in the list.
If we go too far and ask for a non-existent element we get no output. (Technically the result is the built-in Python None
object, so we can test for that.)
Combinations may be taken from a set of consecutive integers. \(\set{1,\,2,\,3,\dots,\,n}\) would be a natural choice, but you will eventually find it much easier (and natural) to start with \(0\) and use \(\set{0,\,1,\,2,\dots,\,n-1}\text{.}\)