The Python math.comb() method is used to calculate the number of combinations of "k" items chosen from a set of "n" items, where order does not matter, and repetition is not allowed.
Mathematically, the number of combinations is represented by the binomial coefficient, often denoted as C(n,k), and is calculated using the formula −
C(n,k) = n!/k!(n-k)!
Where,
Following is the basic syntax of the Python math.comb() method −
math.comb(n, k)Parameters
This method accepts the following parameters −
n − This is an integer representing the total number of items.
k − This is an integer representing the number of items to choose.
The method returns an integer value representing the number of combinations of choosing k items from n items.
Example 1In the following example, we are calculating the number of combinations of 2 items chosen from a set of 5 items −
import math result = math.comb(5, 2) print("The result obtained is:",result)Output
The output obtained is as follows −
The result obtained is: 10Example 2
Here, we are calculating the number of combinations of 0 items chosen from a set of 6 items, which equals 1. This is because there is only one way to choose zero items from a set −
import math result = math.comb(6, 0) print("The result obtained is:",result)Output
Following is the output of the above code −
The result obtained is: 1Example 3
In this example, we use variables "n" and "k" to represent the number of items in the set and the number of items to choose, respectively. We then calculate the number of combinations accordingly −
import math n = 8 k = 3 result = math.comb(n, k) print("The result obtained is:",result)Output
We get the output as shown below −
The result obtained is: 56Example 4
The math.comb() method automatically retrieves the result as an integer, even if the arguments are fractional.
Now, we calculate the number of combinations of 2 items chosen from a set of 7 items −
import math result = math.comb(7, 2) print("The result obtained is:",result)Output
The result produced is as shown below −
The result obtained is: 21
python_maths.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4