GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithms/dp/knapsack.py at master · deba999/algorithms Expand file tree/ Copy pathknapsack.pyMore file actions 38 lines (29 loc) · 1.23 KB / Copy pathknapsack.pyFile metadata and controls38 lines (29 loc) · 1.23 KB 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 """ Given the capacity of the knapsack and items specified by weights and values, return the maximum summarized value of the items that can be fit in the knapsack. Example: capacity = 5, items(value, weight) = [(60, 5), (50, 3), (70, 4), (30, 2)] result = 80 (items valued 50 and 30 can both be fit in the knapsack) The time complexity is O(n * m) and the space complexity is O(m), where n is the total number of items and m is the knapsack's capacity. """ class Item(object): def __init__(self, value, weight): self.value = value self.weight = weight def get_maximum_value(items, capacity): dp = [0] * (capacity + 1) for item in items: dp_tmp = [total_value for total_value in dp] for current_weight in range(capacity + 1): total_weight = current_weight + item.weight if total_weight <= capacity: dp_tmp[total_weight] = max(dp_tmp[total_weight], dp[current_weight] + item.value) dp = dp_tmp return max(dp) print(get_maximum_value([Item(60, 10), Item(100, 20), Item(120, 30)], 50)) print(get_maximum_value([Item(60, 5), Item(50, 3), Item(70, 4), Item(30, 2)], 5)) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |