MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / knapsack_with_example_solution

Function knapsack_with_example_solution

dynamic_programming/knapsack.py:42–100  ·  view source on GitHub ↗

Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters ---------- * `w`: int, the total maximum weight for the given knapsack problem. * `wt`: list, the vector of weights for all items where ``wt[i]`` is the weight

(w: int, wt: list, val: list)

Source from the content-addressed store, hash-verified

40
41
42def knapsack_with_example_solution(w: int, wt: list, val: list):
43 """
44 Solves the integer weights knapsack problem returns one of
45 the several possible optimal subsets.
46
47 Parameters
48 ----------
49
50 * `w`: int, the total maximum weight for the given knapsack problem.
51 * `wt`: list, the vector of weights for all items where ``wt[i]`` is the weight
52 of the ``i``-th item.
53 * `val`: list, the vector of values for all items where ``val[i]`` is the value
54 of the ``i``-th item
55
56 Returns
57 -------
58
59 * `optimal_val`: float, the optimal value for the given knapsack problem
60 * `example_optional_set`: set, the indices of one of the optimal subsets
61 which gave rise to the optimal value.
62
63 Examples
64 --------
65
66 >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22])
67 (142, {2, 3, 4})
68 >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4])
69 (8, {3, 4})
70 >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4])
71 Traceback (most recent call last):
72 ...
73 ValueError: The number of weights must be the same as the number of values.
74 But got 4 weights and 3 values
75 """
76 if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))):
77 raise ValueError(
78 "Both the weights and values vectors must be either lists or tuples"
79 )
80
81 num_items = len(wt)
82 if num_items != len(val):
83 msg = (
84 "The number of weights must be the same as the number of values.\n"
85 f"But got {num_items} weights and {len(val)} values"
86 )
87 raise ValueError(msg)
88 for i in range(num_items):
89 if not isinstance(wt[i], int):
90 msg = (
91 "All weights must be integers but got weight of "
92 f"type {type(wt[i])} at index {i}"
93 )
94 raise TypeError(msg)
95
96 optimal_val, dp_table = knapsack(w, wt, val, num_items)
97 example_optional_set: set = set()
98 _construct_solution(dp_table, wt, num_items, w, example_optional_set)
99

Callers 1

knapsack.pyFile · 0.85

Calls 2

_construct_solutionFunction · 0.85
knapsackFunction · 0.70

Tested by

no test coverage detected