Skip to content

Commit b3893e2

Browse files
committed
Update README.md and factorial.py
1 parent 1236907 commit b3893e2

File tree

2 files changed

+52
-7
lines changed

2 files changed

+52
-7
lines changed

README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
# Dynamic Programming
3+
4+
## Optimal Substructure Property
5+
6+
It means that the optimal solution to the problem can be formulated from the optimal solution to smaller instances of the same problem.
7+
Example: `f(n) = f(n - 1) + f(n - 2)`. Problem of size n reduced to `n - 1` and `n - 2`.
8+
9+
10+
11+
## Overlapping Subproblems
12+
13+
The smaller problems, which are needed to solve the bigger problem, are called multiple times while solving.
14+
15+
Example: `f(n) = f(n - 1) + f(n - 2)`, `f(n - 1) = f(n - 2) + f(n - 3)`. `f(n - 2)` is required at least twice to solve this.
16+
17+
18+
# References
19+
* https://www.hackerrank.com/topics/dynamic-programming
20+
* https://www.geeksforgeeks.org/dynamic-programming/

factorial.py

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,24 @@
11

22
# Bottom-up and Top-down Dynamic Programming example for Factorial program.
3+
from utils import *
4+
import time
35

46
# Initialize factorial list with all -1's
5-
factorial = [-1 for _ in range(30)]
7+
factorial = [-1 for _ in range(901)]
68

79
# Set 0! to 1
810
factorial[0] = 1
911

12+
def classic_factorial(n):
13+
"""
14+
Factorial function without Dynamic Programming
15+
"""
16+
17+
if n <= 1:
18+
return 1
19+
else:
20+
return n * classic_factorial(n - 1)
21+
1022
def bottom_up_factorial(n):
1123
"""
1224
Tabulation or Bottom-up approach to finding factorial of a number.
@@ -39,12 +51,25 @@ def top_down_factorial(n):
3951

4052
return factorial[n]
4153

54+
def print_time(func_name):
4255

43-
if __name__ == '__main__':
44-
45-
print(bottom_up_factorial(7))
46-
print(bottom_up_factorial(8))
56+
start = get_current_time()
57+
print('Running %s function to compute 900!' % (func_name.__name__, ))
58+
answer = func_name(900)
59+
diff = get_time_diff_ms(start)
60+
print('Execution taken: %f ms' % (diff, ))
4761

48-
print(top_down_factorial(7))
49-
print(top_down_factorial(6))
62+
if __name__ == '__main__':
5063

64+
print_time(classic_factorial)
65+
print_time(bottom_up_factorial)
66+
print_time(top_down_factorial)
67+
68+
# Results
69+
#
70+
# Running classic_factorial function to compute 900!
71+
# Execution taken: 1.060247 ms
72+
# Running bottom_up_factorial function to compute 900!
73+
# Execution taken: 0.600815 ms
74+
# Running top_down_factorial function to compute 900!
75+
# Execution taken: 0.008583 ms

0 commit comments

Comments
 (0)