Let us suppose you received 4 candies from your Halloween trick or treating, e.g., “Kit Kat”, “Snickers”, “Reeses”, and “Crackle”. You are allowed to choose two from this set of 4 candies. How many ways can you do so? Here are the ways:
Note that the order in which you choose them does not matter, so “Kit Kat”, “Snickers” is the same as “Snickers”, “Kit Kat” (which is not listed).
It is easy enough to list the combinations for this small case but what if you had 20 types of candies and you need to choose 5 of them. How can we count the combinations systematically without worrying that you have missed some combination? There is a Python math function for that!
The Python math.comb() function takes two arguments “n” and “k” and returns the number of ways in which k elements can be chosen from a set of n elements. Note that k can be at most n. We read this as “n choose k”. The mathematical formula for “n choose k” is n! / (n-k)!, i.e., it is a ratio of two factorials.
Here is a simple Python program mimicking our candy scenario:
The output will be:
In fact, we can try to see how many different ways there are in choosing different numbers of elements from our set of 4 candies. In other words, we keep n fixed at 4 and vary k from 0 to 4. There is only 1 way to choose 0 elements from 4 (i.e., not choose anything at all). There is also only 1 way to choose 4 elements from 4 (i.e., choose all of them). In between values of k (i.e., 1, 2, and 3) will give intermediate values. Here is a simple program to explore this using a for loop:
The output is:
Thus, there are 4 ways (see second line) to choose 1 candy from the set of all candies (we choose them individually). There are 6 ways to choose 2 candies (what we have seen). Finally, there are 4 ways to choose 3 candies (this is easy to see because if we are choosing 3 candies, we are discarding one of them, and there are 4 ways to discard one).
Here is a program that provides more descriptive output:
The output is:
If you are with us so far you can extend this program to multiple numbers of candies and for each number, exploring all the different ways to choose a given number of candies:
In the above program we are varying both n and k in the math.comb() invocation. This gives us a beautiful pattern:
This is also known as Pascal’s triangle which is usually center-aligned (but you get the idea).
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.