Combinations and Factorials – Python

Mathematical Combinations

The combination formula is this…


with n being the number of items available to you and k the number of items you can pick at one time (where order does not matter).

In other words, if n = 4 (a,b,c,d), and k = 2, it means that we have four items to choose from, and we can only choose two at a time. So the different combinations would be…

a b
a c
a d
b c
b d
c d

Because order does not matter (a b is the same thing as b a) we have a total of 6 possible unique combinations.

Factorials in Python

To calculate the number of combinations we need to use factorials (the ! symbol).

Factorials work like this…

3! = 3 x 2 x 1 = 6
4! = 4 x 3 x 2 x 1 = 24
5! = 5 x 4 x 3 x 2 x 1 = 120
... and so on.

In python, factorials can be found in the math module

from math import factorial

…and can be used like this.

>>> factorial(6)

Python Combination Function

the function looks like this

def combination(n,k):
    return answer

So if we run the function with the above example (n=4 and k=2), we should get the right answer.

>>> combination(4,2)


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s