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

Function knapsack

knapsack/recursive_approach_knapsack.py:20–45  ·  view source on GitHub ↗

Function description is as follows- :param weights: Take a list of weights :param values: Take a list of profits corresponding to the weights :param number_of_items: number of items available to pick from :param max_weight: Maximum weight that could be carried :param index:

(
    weights: list, values: list, number_of_items: int, max_weight: int, index: int
)

Source from the content-addressed store, hash-verified

18
19
20def knapsack(
21 weights: list, values: list, number_of_items: int, max_weight: int, index: int
22) -> int:
23 """
24 Function description is as follows-
25 :param weights: Take a list of weights
26 :param values: Take a list of profits corresponding to the weights
27 :param number_of_items: number of items available to pick from
28 :param max_weight: Maximum weight that could be carried
29 :param index: the element we are looking at
30 :return: Maximum expected gain
31 >>> knapsack([1, 2, 4, 5], [5, 4, 8, 6], 4, 5, 0)
32 13
33 >>> knapsack([3 ,4 , 5], [10, 9 , 8], 3, 25, 0)
34 27
35 """
36 if index == number_of_items:
37 return 0
38 ans1 = 0
39 ans2 = 0
40 ans1 = knapsack(weights, values, number_of_items, max_weight, index + 1)
41 if weights[index] <= max_weight:
42 ans2 = values[index] + knapsack(
43 weights, values, number_of_items, max_weight - weights[index], index + 1
44 )
45 return max(ans1, ans2)
46
47
48if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected