|
| 1 | +# A Python program to find n'th Bell number |
| 2 | +# Approach : Dynamic Programming |
| 3 | +# Abhishek S, 2021 |
| 4 | + |
| 5 | +# ---------------------------------------------------------- |
| 6 | + |
| 7 | +# Problem statement : Given a set of n elements, find the |
| 8 | +# number of ways of partitioning it. |
| 9 | + |
| 10 | +# ---------------------------------------------------------- |
| 11 | + |
| 12 | +# Solution : Used the Dynamic Approach to solve the problem. |
| 13 | + |
| 14 | +# This is the working function which will check and return the |
| 15 | +# nth bell numbers one after another using the Dynamic Programming |
| 16 | +# method |
| 17 | + |
| 18 | +def bellNumber(n): |
| 19 | + |
| 20 | + bell = [[0 for i in range(n+1)] for j in range(n+1)] |
| 21 | + bell[0][0] = 1 |
| 22 | + for i in range(1, n+1): |
| 23 | + |
| 24 | + # Explicitly fill for j = 0 |
| 25 | + bell[i][0] = bell[i-1][i-1] |
| 26 | + |
| 27 | + # Fill for remaining values of j |
| 28 | + for j in range(1, i+1): |
| 29 | + bell[i][j] = bell[i-1][j-1] + bell[i][j-1] |
| 30 | + |
| 31 | + return bell[n][0] |
| 32 | + |
| 33 | +# Driver program |
| 34 | +print ("- Bell Numbers using Dynamic Programming Approach -") |
| 35 | +print ("---------------------------------------------------") |
| 36 | +print () |
| 37 | +z = int(input("Enter the number of numbers you wanna print : ")) |
| 38 | +print () |
| 39 | +print ("---------------------------------------------------") |
| 40 | +print () |
| 41 | +print ("Output : ") |
| 42 | +print () |
| 43 | +for n in range(z): |
| 44 | + print('Bell Number', n, 'is', bellNumber(n)) |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | +# ---------------------------------------------------------- |
| 49 | + |
| 50 | +# Enter the number of numbers you wanna print : 6 |
| 51 | + |
| 52 | +# ---------------------------------------------------------- |
| 53 | + |
| 54 | +# Output : |
| 55 | + |
| 56 | +# Bell Number 0 is 1 |
| 57 | +# Bell Number 1 is 1 |
| 58 | +# Bell Number 2 is 2 |
| 59 | +# Bell Number 3 is 5 |
| 60 | +# Bell Number 4 is 15 |
| 61 | +# Bell Number 5 is 52 |
| 62 | + |
| 63 | +# ---------------------------------------------------------- |
| 64 | + |
| 65 | +# Code contributed by, Abhishek Sharma, 2021 |
0 commit comments