Add knapsack variant to count optimal-value subsets#14536
Add knapsack variant to count optimal-value subsets#14536nickzerjeski wants to merge 3 commits intoTheAlgorithms:masterfrom
Conversation
There was a problem hiding this comment.
Pull request overview
Adds a new knapsack API that returns both the optimal (max) achievable value and the number of distinct optimal selections, extending the existing memoized recursive approach in knapsack/knapsack.py.
Changes:
- Added
knapsack_with_count(...)-> tuple[int, int]that tracks(max_value, count)and aggregates counts on ties. - Added doctests for
knapsack_with_countinknapsack/knapsack.py. - Added unit tests for baseline and tie-counting behavior (0-1 and unbounded variants).
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| knapsack/knapsack.py | Introduces knapsack_with_count and adds typing for allow_repetition in knapsack() |
| knapsack/tests/test_knapsack.py | Adds tests validating returned (max_value, count) for standard and tie scenarios |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| """ | ||
| Return both the maximum knapsack value and the number of optimal subsets. | ||
|
|
||
| The return value is ``(max_value, number_of_optimal_subsets)``. | ||
| If multiple choices produce the same maximum value, their counts are added. | ||
|
|
knapsack/knapsack.py
Outdated
| @lru_cache | ||
| def knapsack_recur(remaining_capacity: int, item_count: int) -> tuple[int, int]: |
| def test_knapsack_with_count(self): | ||
| """ | ||
| test for maximum value and number of optimal subsets | ||
| """ | ||
| cap = 50 | ||
| val = [60, 100, 120] | ||
| w = [10, 20, 30] | ||
| c = len(val) | ||
| assert k.knapsack_with_count(cap, w, val, c) == (220, 1) | ||
| assert k.knapsack_with_count(cap, w, val, c, True) == (300, 1) |
|
Reopening to trigger checklist-based label automation after PR template update. |
|
Updated this PR description to follow the repository checklist template and marked the relevant items. Could a maintainer please apply the standard labels (e.g., "awaiting reviews" / "enhancement")? Label assignment is currently blocked on my side by repository permissions. |
Describe your change:
Add a knapsack variation that returns both the maximum achievable value and the number of distinct optimal selections.
Checklist:
Validation
python -m doctest -v knapsack/knapsack.py(pass)python -m unittest knapsack.tests.test_knapsack -v(pass)Fixes #14463