Comb Function In Python Math Module

Overview:

  • From a set of ‘n’ items, a number of subsets can be formed with item count ‘k’. In other words, ‘k’ number items can be chosen from ‘n’ items, in a number of ways.
  • The function comb() of the Python math module, returns the number of combinations or different ways in which ‘k’ number of items can be chosen from ‘n’ items, without repetitions and without order.
  • The number of combinations returned, is also called as the binomial coefficient. It is the coefficient of the kth term, in the polynomial expansion of the binomial power (1+x)^n.
  • n choose k is given by the formula,  n!/k!(n-k)! where n >=k >= 0.

Example:

# Example Python program that finds number of ways to select 'k' items from

# 'n' items, using the library function comb()

import math

 

itemCount       = 10;

selectItemCount = 5;

 

# Find number of ways to select k items

combinations = math.comb(10, 5);

print("Number of ways to select 'k' items from 'n' items (The binomial coefficient):");

print(combinations);

 

Output:

Number of ways to select 'k' items from 'n' items (The binomial coefficient):

252

 


Copyright 2022 © pythontic.com