|
| 1 | +# To get an insight into naive recursive way to solve the Knapsack problem |
| 2 | + |
| 3 | + |
| 4 | +""" |
| 5 | +A shopkeeper has bags of wheat that each have different weights and different profits. |
| 6 | +eg. |
| 7 | +no_of_items 4 |
| 8 | +profit 5 4 8 6 |
| 9 | +weight 1 2 4 5 |
| 10 | +max_weight 5 |
| 11 | +Constraints: |
| 12 | +max_weight > 0 |
| 13 | +profit[i] >= 0 |
| 14 | +weight[i] >= 0 |
| 15 | +Calculate the maximum profit that the shopkeeper can make given maxmum weight that can |
| 16 | +be carried. |
| 17 | +""" |
| 18 | + |
| 19 | + |
| 20 | +def 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 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + |
| 50 | + import doctest |
| 51 | + |
| 52 | + doctest.testmod() |
0 commit comments