|
1 | | -# Bottom up implementation of Knapsack (using loops) |
| 1 | +''' |
| 2 | +Purpose is if having a bunch of items with a weight and corresponding value to each object. |
| 3 | +Which collection of objects should we choose such that we maximize the value restricted to |
| 4 | +a specific capacity of weight. Bottom up implementation of Knapsack (using loops) |
2 | 5 |
|
3 | | -# Purpose is if having a bunch of items with a weight and corresponding value to each object. |
4 | | -# Which collection of objects should we choose such that we maximize the value restricted to |
5 | | -# a specific capacity of weight |
| 6 | +Time Complexity: O(nC), pseudo-polynomial |
6 | 7 |
|
7 | | -# Programmed by Aladdin Persson <aladdin dot persson at hotmail dot com> |
8 | | -# 2020-02-15 Initial programming |
| 8 | +Programmed by Aladdin Persson <aladdin dot persson at hotmail dot com> |
| 9 | + 2020-02-15 Initial programming |
| 10 | +''' |
9 | 11 |
|
10 | 12 | def find_opt(i, c, M, values, items, weights): |
11 | 13 | if i <= 0 or c <= 0: |
@@ -46,12 +48,12 @@ def knapsack(n, C, weights, values): |
46 | 48 | return M[n][C], items[::-1] |
47 | 49 |
|
48 | 50 |
|
49 | | -if __name__ == '__main__': |
50 | | - # Run small example |
51 | | - weights = [1,2,4,2,5] |
52 | | - values = [5,3,5,3,2] |
53 | | - n = len(weights) |
54 | | - capacity = 3 |
55 | | - total_value, items = knapsack(n, capacity, weights, values) |
56 | | - print('Items at the end: ' + str(items)) |
57 | | - print('With total value: ' + str(total_value)) |
| 51 | +# if __name__ == '__main__': |
| 52 | +# # Run small example |
| 53 | +# weights = [1,2,4,2,5] |
| 54 | +# values = [5,3,5,3,2] |
| 55 | +# n = len(weights) |
| 56 | +# capacity = 3 |
| 57 | +# total_value, items = knapsack(n, capacity, weights, values) |
| 58 | +# print('Items at the end: ' + str(items)) |
| 59 | +# print('With total value: ' + str(total_value)) |
0 commit comments