1010https://en.wikipedia.org/wiki/Knapsack_problem
1111"""
1212
13- from dataclasses import dataclass
14- from typing import List , Tuple
1513import heapq
14+ from dataclasses import dataclass
1615
1716
1817@dataclass
@@ -29,7 +28,7 @@ class Node:
2928 bound : float
3029
3130
32- def calculate_bound (node : Node , capacity : int , items : List [Item ]) -> float :
31+ def calculate_bound (node : Node , capacity : int , items : list [Item ]) -> float :
3332 """
3433 Calculate the upper bound of profit for a node using
3534 the fractional knapsack approach.
@@ -48,14 +47,16 @@ def calculate_bound(node: Node, capacity: int, items: List[Item]) -> float:
4847
4948 if index < len (items ):
5049 profit_bound += (
51- (capacity - total_weight ) * items [index ].value / items [index ].weight
50+ (capacity - total_weight )
51+ * items [index ].value
52+ / items [index ].weight
5253 )
5354
5455 return profit_bound
5556
5657
5758def knapsack_branch_and_bound (
58- capacity : int , weights : List [int ], values : List [int ]
59+ capacity : int , weights : list [int ], values : list [int ]
5960) -> int :
6061 """
6162 Solve the 0/1 Knapsack problem using the Branch and Bound technique.
@@ -66,7 +67,7 @@ def knapsack_branch_and_bound(
6667 items = [Item (weight = w , value = v ) for w , v in zip (weights , values )]
6768 items .sort (key = lambda item : item .value / item .weight , reverse = True )
6869
69- priority_queue : List [ Tuple [float , Node ]] = []
70+ priority_queue : list [ tuple [float , Node ]] = []
7071
7172 root = Node (level = - 1 , profit = 0 , weight = 0 , bound = 0.0 )
7273 root .bound = calculate_bound (root , capacity , items )
@@ -97,7 +98,9 @@ def knapsack_branch_and_bound(
9798
9899 include_node .bound = calculate_bound (include_node , capacity , items )
99100 if include_node .bound > max_profit :
100- heapq .heappush (priority_queue , (- include_node .bound , include_node ))
101+ heapq .heappush (
102+ priority_queue , (- include_node .bound , include_node )
103+ )
101104
102105 # Exclude next item
103106 exclude_node = Node (
@@ -109,6 +112,8 @@ def knapsack_branch_and_bound(
109112
110113 exclude_node .bound = calculate_bound (exclude_node , capacity , items )
111114 if exclude_node .bound > max_profit :
112- heapq .heappush (priority_queue , (- exclude_node .bound , exclude_node ))
115+ heapq .heappush (
116+ priority_queue , (- exclude_node .bound , exclude_node )
117+ )
113118
114119 return max_profit
0 commit comments