Categories

# 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)
720
```

## Python Combination Function

the function looks like this

```def combination(n,k):
numerator=factorial(n)
denominator=(factorial(k)*factorial(n-k))
```>>> combination(4,2)