|
| 1 | +def knapsack(profit, weight, capacity): |
| 2 | + """ |
| 3 | + Here Knapsack problem has been implemented using Greedy Approach |
| 4 | + where the weight and and corresponding profit of some items has been |
| 5 | + given. And also the maximum capacity of a sack(bag) is given. we have |
| 6 | + to take items so that capacity does not exceed and we get maximum profit. |
| 7 | + For more information visit: <https://en.wikipedia.org/wiki/Knapsack_problem> |
| 8 | +
|
| 9 | + :param profit: array of profit of the items |
| 10 | + :param weight: array of weight of the items |
| 11 | + :param capacity: capacity of the sack |
| 12 | + :return: maximum profit and the fraction of items |
| 13 | + """ |
| 14 | + |
| 15 | + # array of profit/weight ratio |
| 16 | + ratio = [v / w for v, w in zip(profit, weight)] |
| 17 | + |
| 18 | + # a list of (0, 1, ..., n-1) |
| 19 | + index = list(range(len(profit))) |
| 20 | + |
| 21 | + # index is sorted according to ratio in descending order |
| 22 | + index.sort(key=lambda i: ratio[i], reverse=True) |
| 23 | + |
| 24 | + # max_profit is the maximum profit gained |
| 25 | + max_profit = 0 |
| 26 | + |
| 27 | + # fraction is the fraction in which items should be taken |
| 28 | + fraction = [0] * len(profit) |
| 29 | + |
| 30 | + for i in index: |
| 31 | + if weight[i] <= capacity: |
| 32 | + fraction[i] = 1 |
| 33 | + max_profit += profit[i] |
| 34 | + capacity -= weight[i] |
| 35 | + else: |
| 36 | + fraction[i] = capacity / weight[i] |
| 37 | + max_profit += profit[i] * fraction[i] |
| 38 | + break |
| 39 | + |
| 40 | + return max_profit, fraction |
| 41 | + |
| 42 | + |
| 43 | +def main(): |
| 44 | + # profit is array of profit of the items |
| 45 | + # weight is array of weight of the items |
| 46 | + # capacity is capacity of the sack |
| 47 | + |
| 48 | + profit = [50, 60, 80] |
| 49 | + weight = [10, 30, 20] |
| 50 | + capacity = 50 |
| 51 | + |
| 52 | + # max_profit is the maximum profit gained |
| 53 | + # fraction is the fraction in which items should be taken |
| 54 | + max_profit, fraction = knapsack(profit, weight, capacity) |
| 55 | + print('Maximum profit:', max_profit) |
| 56 | + print('Items should be taken in fraction of:', fraction) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + main() |
0 commit comments