Program to implement the fractional knapsack problem in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lists, weights and values of same length and another value capacity. The weights[i] and values[i] represent the weight and value of ith element. So if we can take at most capacity weights, and that we can take a fraction of an item's weight with proportionate value, we have to find the maximum amount of value we can get (rounded down to the nearest integer)

So, if the input is like weights = [6, 7, 3] values = [110, 120, 2] capacity = 10, then the output will be 178.

To solve this, we will follow these steps −

• res := 0

• make a list of pairs P with weights and values, and sort them based on values per weight

• for each pair in P, do

• cif capacity is 0, then
• come out from the loop

• if pair[0] > capacity, then

• res := res + quotient of (pair[1] /(pair[0] / capacity)

• capacity := 0

• otherwise when pair[0] <= capacity, then

• res := res + pair[1]

• capacity := capacity - pair[0]

• return floor value of res

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution:
def solve(self, weights, values, capacity):
res = 0
for pair in sorted(zip(weights, values), key=lambda x: - x[1]/x[0]):
if not bool(capacity):
break
if pair[0] > capacity:
res += int(pair[1] / (pair[0] / capacity))
capacity = 0
elif pair[0] <= capacity:
res += pair[1]
capacity -= pair[0]
return int(res)

ob = Solution()
weights = [6, 7, 3]
values = [110, 120, 2]
capacity = 10
print(ob.solve(weights, values, capacity))

Input

[6, 7, 3],[110, 120, 2],10

Output

230
Published on 08-Oct-2020 14:07:37