-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Catalan_DP.py
55 lines (39 loc) · 1.23 KB
/
Catalan_DP.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
''' This program calculates nth Catalan number using Dynamic programming.
The solutions to the nth Catalan number is calculated in bottom-up manner.
There by reducing the time complexity.'''
# This function returns nth catalan number
def n_catalan(number):
# Makes an array to store the catalan numbers
array = [0] * (number + 1)
# Base cases
array[0] = 1
if(number == 0):
return array[0]
array[1] = 1
# Using DP recursive solution to get nth catalan number
for i in range(2, number + 1):
for j in range(0, i):
array[i] += array[j] * array[i - j - 1]
# Return the nth catalan number
return array[number]
## Drivers code
if __name__=="__main__":
##Take number as input from the user
number = int(input("Enter a number: "))
## Check if the number is non-negative.
if(number < 0):
print("\nPlease enter a non-negative number.")
exit()
## Call the function
catalan = n_catalan(number)
## Print the nth catalan number
print("\nCatalan number at index " + str(number) + " is " + str(catalan))
'''
Sample I/O:
1)
Enter a number: 10
Catalan number at index 10 is 16796
2)
Enter a number: -2
Please enter a non-negative number.
'''