
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to calculate catalan numbers with the method of Binominal Coefficients using Python?
Catalan numbers are defined as a sequence of natural numbers that can be used to find the number of possibilities of various combinations. The below formula is used to calculate catalan number using the binomial coefficient ( denoted as (nk) and represents the number of ways to choose k items from n )-
For example, if the input parameter n is given 6, the output would be 142, that is calculated using the above formula in the following way:
C(6)=C(0)C(5) + C(1)C(4) + C(2)C(3) + C(3)C(2) + C(4)C(1) + C(5)C(0)
Following are the two main methods used to calculate the Catalan number using binomial coefficients:
- Calculate Catalan Numbers Using math.comb()
- Calculate Catalan Numbers By Defining a Binomial Function
Calculate Catalan Numbers Using math.comb()
The math.comb() is a built-in function that is used to calculate the binomial coefficient. It accepts natural numbers (non-negative numbers) as input and returns an integer representing the number of combinations.
Example
In the following example, we will use the math.comb() function to calculate binomial coefficient, which then divided by (n+1) using // operator to calculate catalan number for the first 10 natural numbers:
import math def catalan_number(n): #math.comb(2 * n, n) calculates the binomial coefficient and //(n+1) performs integer division to calculate Catalan number return math.comb(2 * n, n) // (n + 1) for i in range(10): print(f"Catalan({i}) =", catalan_number(i))
The output returned by the above code is as follows -
Catalan(0) = 1 Catalan(1) = 1 Catalan(2) = 2 Catalan(3) = 5 Catalan(4) = 14 Catalan(5) = 42 Catalan(6) = 132 Catalan(7) = 429 Catalan(8) = 1430 Catalan(9) = 4862
Calculate Catalan Numbers By Defining a Binomial Function
Unlike the above example, in this example we will create a function that calculates the binomial coefficient by initializing a variable with 1, and iteratively multiplying and dividing it k times to avoid calculating factorials.
Example
Here, we calculate the catalan number for the first five natural numbers(n=5), where the binomial coefficient is calculated using the created function and then divided by (n+1):
# Function to calculate binomial coefficient # Here, n=5 and k=2*n def binomial_coeff(k, n): # Initialize res as 1 res = 1 for i in range(n): res *= (k - i) res //= (i + 1) return res # Function to calculate catalan numbers def catalan_number(n): return binomial_coeff(2 * n, n) // (n + 1) print("Catalan(5) =", catalan_number(5))
The output returned by the above code is as follows -
Catalan(5) = 42