Last active
September 29, 2017 07:36
-
-
Save thundergolfer/e5476b3c8a6253917f42ac822f44b5e7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def unbounded_knapsack(items, C): | |
| """ | |
| items List[item], where 'item' is a named tuple -> (val=4, cost=10) | |
| C int, where 'C' stands for capacity | |
| Note: This implementation also stores the optimal group of items at each capacity value | |
| """ | |
| dp = [(0, [])] * (C + 1) | |
| used = [] | |
| items.sort(key=lambda x: x.cost) | |
| for c in range(1, C + 1): | |
| best = 0 | |
| for item in items: | |
| if item.cost <= c: | |
| option = dp[c - item.cost][0] + item.val | |
| if option > best: | |
| best = option | |
| used = dp[c - item.cost][1] + [item] | |
| else: | |
| break | |
| dp[c] = (best, used) | |
| return dp[C][0], dp[C][1] |
Author
Author
If you pre-sort the candidate items in ascending by cost, you can avoid looping pointlessly through the rest of the items if you find one is already too big for the current c.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unbounded knapsack is where you can select an item from the candidate group more than once.
The code is actually almost more simple than 1/0 knapsack.