Repository navigation
Conversation
knapsack returned dp[n][w_] with w_ being the loop variable, so a capacity of 0 or no items raised UnboundLocalError. Return dp[n][w] instead.
This branch has not been deployed
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Describe your change
dynamic_programming/knapsack.py::knapsackreturneddp[n][w_], wherew_is the loop variable over capacities. With a capacity of 0 or with no items the loop never runs, soknapsack(0, [1], [5], 1)andknapsack_with_example_solution(5, [], [])raisedUnboundLocalError. It now returnsdp[n][w], which is the same cell whenever the loop ran.I added two doctests to
knapsack_with_example_solutionfor those cases (they fail onmaster); the added doctests are the regression evidence for this one function, so I kept them in the same PR. Over 5000 random instances (capacity 0 to 15, 0 to 6 items) the value matches a one-dimensional DP and the returned item set fits the capacity and sums to the value.ruff check,ruff format --checkandpython -m doctestpass.Written with the help of Claude Code (Claude Sonnet 5.5).
Checklist