HomeLanguagesPython – math.comb() method

Python – math.comb() method

Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.comb() method in Python is used to get the number of ways to choose k items from n items without repetition and without order. It basically evaluates to n! / (k! * (n – k)!) when k n. It is also known as binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x)n.
This method is new in Python version 3.8.

Syntax: math.comb(n, k)

Parameters:
n: A non-negative integer
k: A non-negative integer

Returns: an integer value which represents the number of ways to choose k items from n items without repetition and without order.

Code #1: Use of math.comb() method




# Python Program to explain math.comb() method
  
# Importing math module
import math
  
n = 10
k = 2
  
# Get the number of ways to choose
# k items from n items without
# repetition and without order
nCk = math.comb(n, k)
print(nCk)
  
n = 5
k = 3
  
# Get the number of ways to choose
# k items from n items without
# repetition and without order
nCk = math.comb(n, k)
print(nCk)


Output:

45
10

Code #2: When k > n




# Python Program to explain math.comb() method
  
# Importing math module
import math
  
# When k > n 
# math.comb(n, k) returns 0.
n = 3
k = 5
  
# Get the number of ways to choose
# k items from n items without
# repetition and without order
nCk = math.comb(n, k)
print(nCk)


Output:

0

Code #3: Use of math.comb() method to find coefficient of k-th term in binomial expansion of expression (1 + x)n




# Python Program to explain math.comb() method
  
# Importing math module
import math
  
n = 5
k = 2
  
# Find the coefficient of k-th
# term in the expansion of 
# expression (1 + x)^n
nCk = math.comb(n, k)
print(nCk)
  
n = 8
k = 3
  
# Find the coefficient of k-th
# term in the expansion of 
# expression (1 + x)^n
nCk = math.comb(n, k)
print(nCk)


Output:

10
56

Reference: Python math library

RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS