Catalan Number in Python – Iterative Approach (Factorial)

In this tutorial, we will be learning about a new topic i.e Catalan Number in Python. So, you can grab an idea on what is a Catalan number and how to generate Catalan numbers in Python.

Catalan Number in Python

Catalan number is a sequence of positive integers, such that nth term in the sequence, denoted Cn, which is given by the following formula: Cn = (2n)! / ((n + 1)!n!)

For generating Catalan numbers up to an upper limit which is specified by the user we must know:

1.Knowledge of calculating factorial of a number
2.The concept of Declaring local functions inside the global functions.

For 1st you may refer to How to calculate Factorial

Now let’s discuss the second one i.e the declaration of local function inside a global function.
SYNTAX:

def func1():                 - global function
     def func():             - local function
      ------

The disadvantages by using nested functions are, the inner function is declared in the local scope and we can not access it outside the outer function, therefore, its usage is restricted to local scope.



SOURCE CODE- CATALAN NUMBER in Python

def catalan(n):
        def hello(x):
            fact=1
            for i in range(1,x+1):
                fact*=i
            return fact    
        p=hello(2*n)//(hello(n)*hello(n+1))
        print p
    

# main
n=int(raw_input())
catalan(n)

Here in the above code, The inner local function is to calculate factorial and the outer global function prints the corresponding catalan number as input by the user.

Input: 5
Output: 42

Finally, you can also, learn,

Get factorial of any number

Factorial of a large number

 

Leave a Reply

Your email address will not be published. Required fields are marked *