How does math.comb() work in Python?
The in-built math.comb() function from the math module in Python is used to find the total number of unordered combinations to choose k amount of items from n items.
Syntax
math.comb(n,k)
Parameters and return values
This function requires two positive integers, n and k, as parameters.
-
If the passed parameters are negative, a
ValueErrorarises. If the parameters are not integers, aTypeErrorarises. -
If k > n,
0is returned.
Code
Example 1
import mathpeople = 6chairs = 3# Number of possible combinations of 6 different people# being seated in 3 chairsprint(math.comb(people, chairs))
Example 2
import mathpeople = 6chairs = 7# Return value is 0 when# k(number ofchairs) > n(number of people)print(math.comb(people, chairs))