-
-
Notifications
You must be signed in to change notification settings - Fork 49.8k
Added branch_and_bound Algorithm #14045
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
iamdevdhanush
wants to merge
4
commits into
TheAlgorithms:master
Choose a base branch
from
iamdevdhanush:branch_and_bound
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
a6fb347
Added branch_and_bound Algorithm
d35fe4d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] ccef627
Update knapsack_branch_and_bound.py
iamdevdhanush 1d1296d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| """ | ||
| Branch and Bound solution for the 0/1 Knapsack problem. | ||
|
|
||
| This implementation uses a best-first search strategy and prunes | ||
| non-promising branches using an upper bound calculated via the | ||
| fractional knapsack (greedy) approach. | ||
|
|
||
| References: | ||
| https://en.wikipedia.org/wiki/Branch_and_bound | ||
| https://en.wikipedia.org/wiki/Knapsack_problem | ||
| """ | ||
|
|
||
| import heapq | ||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass | ||
| class Item: | ||
| weight: int | ||
| value: int | ||
|
|
||
|
|
||
| @dataclass | ||
| class Node: | ||
| level: int | ||
| profit: int | ||
| weight: int | ||
| bound: float | ||
|
|
||
|
|
||
| def calculate_bound(node: Node, capacity: int, items: list[Item]) -> float: | ||
| """ | ||
| Calculate the upper bound of profit for a node using | ||
| the fractional knapsack approach. | ||
| """ | ||
| if node.weight >= capacity: | ||
| return 0.0 | ||
|
|
||
| profit_bound = float(node.profit) | ||
| total_weight = node.weight | ||
| index = node.level + 1 | ||
|
|
||
| while index < len(items) and total_weight + items[index].weight <= capacity: | ||
| total_weight += items[index].weight | ||
| profit_bound += items[index].value | ||
| index += 1 | ||
|
|
||
| if index < len(items): | ||
| profit_bound += ( | ||
| (capacity - total_weight) * items[index].value / items[index].weight | ||
| ) | ||
|
|
||
| return profit_bound | ||
|
|
||
|
|
||
| def knapsack_branch_and_bound( | ||
| capacity: int, weights: list[int], values: list[int] | ||
| ) -> int: | ||
| """ | ||
| Solve the 0/1 Knapsack problem using the Branch and Bound technique. | ||
|
|
||
| >>> knapsack_branch_and_bound(50, [10, 20, 30], [60, 100, 120]) | ||
| 220 | ||
| """ | ||
| items = [Item(weight=w, value=v) for w, v in zip(weights, values)] | ||
| items.sort(key=lambda item: item.value / item.weight, reverse=True) | ||
|
|
||
| priority_queue: list[tuple[float, Node]] = [] | ||
|
|
||
| root = Node(level=-1, profit=0, weight=0, bound=0.0) | ||
| root.bound = calculate_bound(root, capacity, items) | ||
|
|
||
| heapq.heappush(priority_queue, (-root.bound, root)) | ||
| max_profit = 0 | ||
|
|
||
| while priority_queue: | ||
| _, current = heapq.heappop(priority_queue) | ||
|
|
||
| if current.bound <= max_profit: | ||
| continue | ||
|
|
||
| next_level = current.level + 1 | ||
| if next_level >= len(items): | ||
| continue | ||
|
|
||
| # Include next item | ||
| include_node = Node( | ||
| level=next_level, | ||
| profit=current.profit + items[next_level].value, | ||
| weight=current.weight + items[next_level].weight, | ||
| bound=0.0, | ||
| ) | ||
|
|
||
| if include_node.weight <= capacity: | ||
| max_profit = max(max_profit, include_node.profit) | ||
|
|
||
| include_node.bound = calculate_bound(include_node, capacity, items) | ||
| if include_node.bound > max_profit: | ||
| heapq.heappush(priority_queue, (-include_node.bound, include_node)) | ||
|
|
||
| # Exclude next item | ||
| exclude_node = Node( | ||
| level=next_level, | ||
| profit=current.profit, | ||
| weight=current.weight, | ||
| bound=0.0, | ||
| ) | ||
|
|
||
| exclude_node.bound = calculate_bound(exclude_node, capacity, items) | ||
| if exclude_node.bound > max_profit: | ||
| heapq.heappush(priority_queue, (-exclude_node.bound, exclude_node)) | ||
|
|
||
| return max_profit | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As there is no test file in this pull request nor any test function or class in the file
knapsack/knapsack_branch_and_bound.py, please provide doctest for the functioncalculate_bound