Skip to content

Commit d952044

Browse files
Merge pull request #178 from abhisheks008/main
Fractional Knapsack Problem
2 parents cc995ad + 120c628 commit d952044

File tree

3 files changed

+179
-0
lines changed

3 files changed

+179
-0
lines changed
10.5 KB
Loading
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Fractional Knapsack Problem using Brute Force Method
2+
Language used : **Python 3**
3+
4+
## 🎯 Aim
5+
The aim of this script is to find out the maximum total value in the knapsack.
6+
7+
## 👉 Purpose
8+
The main purpose of this script is to show the implementation of Brute Force Method to find out the maximum total value in the knapsack.
9+
10+
## 📄 Description
11+
Given weights and values of n items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In the 0-1 Knapsack problem, we are not allowed to break items. We either take the whole item or don’t take it.
12+
```
13+
Input:
14+
Items as (value, weight) pairs
15+
arr[] = {{60, 10}, {100, 20}, {120, 30}}
16+
Knapsack Capacity, W = 50;
17+
18+
Output:
19+
Maximum possible value = 240
20+
by taking items of weight 10 and 20 kg and 2/3 fraction
21+
of 30 kg. Hence total price will be 60+100+(2/3)(120) = 240
22+
```
23+
24+
## 📈 Workflow of the script
25+
- `ItemValue` - This function returns the item values of the data class.
26+
- `FractionalKnapSack` - This function is the main architecture to solve the program.
27+
- `__main__` - This is the driver code of the script.
28+
29+
## 📃 Explanation
30+
In Fractional Knapsack, we can break items for maximizing the total value of knapsack. This problem in which we can break an item is also called the fractional knapsack problem.
31+
```
32+
Input : Same as above
33+
Output : Maximum possible value = 240 By taking full items of 10 kg, 20 kg and 2/3rd of last item of 30 kg
34+
```
35+
A brute-force solution would be to try all possible subset with all different fraction but that will be too much time taking.
36+
37+
## 🧮 Algorithm
38+
- An efficient solution is to use Greedy approach. The basic idea of the greedy approach is to calculate the ratio value/weight for each item and sort the item on basis of this ratio.
39+
- Then take the item with the highest ratio and add them until we can’t add the next item as a whole and at the end add the next item as much as we can. Which will always be the optimal solution to this problem.
40+
- A simple code with our own comparison function can be written as follows, please see sort function more closely, the third argument to sort function is our comparison function which sorts the item according to value/weight ratio in non-decreasing order.
41+
- After sorting we need to loop over these items and add them in our knapsack satisfying above-mentioned criteria.
42+
43+
## 💻 Input and Output
44+
```
45+
- Fractional Knapsack Problem using Brute Force Method -
46+
-----------------------------------------------------
47+
48+
The values given :
49+
[60, 40, 100, 120]
50+
-----------------------------------------------------
51+
The corresponding weights are :
52+
[10, 40, 20, 30]
53+
-----------------------------------------------------
54+
The maximum capacity can be :
55+
50
56+
57+
-----------------------------------------------------
58+
59+
Output :
60+
Maximum value in Knapsack = 240.0
61+
```
62+
63+
![](https://github.com/abhisheks008/PyAlgo-Tree/blob/main/Knapsack/Fractional%20Knapsack/Images/frac1.PNG)
64+
65+
66+
## ⏰ Time and Space complexity
67+
- **Time Complexity:** `O(n log n)`.
68+
69+
---------------------------------------------------------------
70+
## 🖋️ Author
71+
**Code contributed by, _Abhishek Sharma_, 2021 [@abhisheks008](github.com/abhisheks008)**
72+
73+
[![forthebadge made-with-python](http://ForTheBadge.com/images/badges/made-with-python.svg)](https://www.python.org/)
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
# Python3 program to solve fractional
2+
# Knapsack Problem
3+
4+
# Problem Statement : Given weights and values of n items,
5+
# we need to put these items in a
6+
# knapsack of capacity W to get the
7+
# maximum total value in the knapsack.
8+
9+
# -----------------------------------------------------------------
10+
11+
# Approach : Brute Force Method
12+
# Abhishek S, 2021
13+
14+
# -----------------------------------------------------------------
15+
16+
# Solution : Using the Brute Force method we can figure out the solution
17+
18+
19+
# This function returns the item values of the data class
20+
class ItemValue:
21+
22+
"""Item Value DataClass"""
23+
24+
def __init__(self, wt, val, ind):
25+
self.wt = wt
26+
self.val = val
27+
self.ind = ind
28+
self.cost = val // wt
29+
30+
def __lt__(self, other):
31+
return self.cost < other.cost
32+
33+
# Greedy Approach
34+
35+
# this function is the main architecture to solve the program.
36+
class FractionalKnapSack:
37+
38+
"""Time Complexity O(n log n)"""
39+
def getMaxValue(wt, val, capacity):
40+
"""function to get maximum value """
41+
iVal = []
42+
for i in range(len(wt)):
43+
iVal.append(ItemValue(wt[i], val[i], i))
44+
45+
# sorting items by value
46+
iVal.sort(reverse=True)
47+
48+
totalValue = 0
49+
for i in iVal:
50+
curWt = int(i.wt)
51+
curVal = int(i.val)
52+
if capacity - curWt >= 0:
53+
capacity -= curWt
54+
totalValue += curVal
55+
else:
56+
fraction = capacity / curWt
57+
totalValue += curVal * fraction
58+
capacity = int(capacity - (curWt * fraction))
59+
break
60+
return totalValue
61+
62+
63+
# Driver Code
64+
if __name__ == "__main__":
65+
wt = [10, 40, 20, 30]
66+
val = [60, 40, 100, 120]
67+
capacity = 50
68+
print ("- Fractional Knapsack Problem using Brute Force Method - ")
69+
print ("-----------------------------------------------------")
70+
print ()
71+
print ("The values given : ")
72+
print (val)
73+
print ("-----------------------------------------------------")
74+
print ("The corresponding weights are :")
75+
print (wt)
76+
print ("-----------------------------------------------------")
77+
print ("The maximum capacity can be : ")
78+
print (capacity)
79+
print ()
80+
print ("-----------------------------------------------------")
81+
print ()
82+
print ("Output : ")
83+
# Function call
84+
maxValue = FractionalKnapSack.getMaxValue(wt, val, capacity)
85+
print("Maximum value in Knapsack =", maxValue)
86+
87+
88+
# -----------------------------------------------------------------
89+
# Input given :
90+
# The values given :
91+
# [60, 40, 100, 120]
92+
# -----------------------------------------------------
93+
# The corresponding weights are :
94+
# [10, 40, 20, 30]
95+
# -----------------------------------------------------
96+
# The maximum capacity can be :
97+
# 50
98+
99+
# -----------------------------------------------------
100+
# Output :
101+
# Maximum total value of the Knapsack :
102+
# 240.0
103+
104+
# -----------------------------------------------------------------
105+
106+
# Code contributed by, Abhishek Sharma, 2021

0 commit comments

Comments
 (0)