|
1 | 1 |
|
2 | 2 | # Bottom-up and Top-down Dynamic Programming example for Factorial program. |
| 3 | +from utils import * |
| 4 | +import time |
3 | 5 |
|
4 | 6 | # Initialize factorial list with all -1's |
5 | | -factorial = [-1 for _ in range(30)] |
| 7 | +factorial = [-1 for _ in range(901)] |
6 | 8 |
|
7 | 9 | # Set 0! to 1 |
8 | 10 | factorial[0] = 1 |
9 | 11 |
|
| 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 | + |
10 | 22 | def bottom_up_factorial(n): |
11 | 23 | """ |
12 | 24 | Tabulation or Bottom-up approach to finding factorial of a number. |
@@ -39,12 +51,25 @@ def top_down_factorial(n): |
39 | 51 |
|
40 | 52 | return factorial[n] |
41 | 53 |
|
| 54 | +def print_time(func_name): |
42 | 55 |
|
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, )) |
47 | 61 |
|
48 | | - print(top_down_factorial(7)) |
49 | | - print(top_down_factorial(6)) |
| 62 | +if __name__ == '__main__': |
50 | 63 |
|
| 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