
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to implement the 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
- Related Articles
- Fractional Knapsack Problem
- C++ Program to Solve the Fractional Knapsack Problem
- Python Program for 0-1 Knapsack Problem
- C++ Program to Solve the 0-1 Knapsack Problem
- C++ Program to Solve Knapsack Problem Using Dynamic Programming
- 0-1 Knapsack Problem in C?
- Program to find maximum value we can get in knapsack problem by taking multiple copies in Python
- C++ Program to Implement Network_Flow Problem
- C++ Program to Implement Traveling Salesman Problem using Nearest Neighbour Algorithm
- Program to Implement Queue in Python
- Python Program for Activity Selection Problem
- Python Program for Subset Sum Problem
- Python Program to Implement Binomial Tree
- Python Program to Implement a Stack
- Python Program to Implement Shell Sort
