
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Fractional Knapsack Problem in Python
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]
- cif capacity is 0, then
return floor value of res
Let us see the following implementation to get better understanding −
Example
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