Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to efficiently calculate the nth Catalan number, in Python?

"""
This implementation demonstrates how
to efficiently calculate the nth
Catalan number. For instance, 
the nth catalan number gives the 
number of unique binary search trees 
which has exactly n nodes of unique values
between 1 and n.

Let us denote it by Cn:
C0 = 1 and Cn+1 = 2(2n+1)Cn/(n+2)

More info at:
https://en.wikipedia.org/wiki/Catalan_number

Time complexity: O(n)
Space complexity: O(1)
"""


def C_n(n):
    C = 1
    for i in range(0, n):
        C = C * 2*(2*i+1)/(i+2)
    return int(C)


print("C1 =", C_n(1))  # C1 = 1
print("C3 =", C_n(3))  # C3 = 5
Comment

PREVIOUS NEXT
Code Example
Python :: access django server from another machine 
Python :: python open file for reading and writing 
Python :: nested loop in list comprehension 
Python :: stack queue in python 
Python :: label change in tkinter 
Python :: import django value 
Python :: slug url 
Python :: python count variable and put the count in a column of data frame 
Python :: numpy average 
Python :: python print green 
Python :: fasttext python 
Python :: pandas save dataframe to csv in python 
Python :: round off to two decimal places python 
Python :: opencv google colab 
Python :: charat in python 
Python :: remove new line character from string python 
Python :: number of days in a month python 
Python :: Python Requests Library Patch Method 
Python :: Command errored out with exit status 1: 
Python :: python copy to clipboard command 
Python :: camel case in python 
Python :: deep copy a dataframe 
Python :: huggingface transformers change download path 
Python :: pd.read_csv 
Python :: map and filter in python 
Python :: Python NumPy swapaxis Function Example 
Python :: Custom x, y-ticks using plt 
Python :: word embedding python 
Python :: str replace python regex 
Python :: get every item but the last item of python list 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =