Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
afnan47
GitHub Repository: afnan47/sem7
Path: blob/main/DAA Python/3_fractional_knapsack.py
418 views
1
def fractional_knapsack():
2
weights=[10,20,30]
3
values=[60,100,120]
4
capacity=50
5
res=0
6
# Pair : [Weight,value]
7
for pair in sorted(zip(weights,values), key= lambda x: x[1]/x[0], reverse=True):
8
if capacity<=0: # Capacity completed - Bag fully filled
9
break
10
if pair[0]>capacity: # Current's weight with highest value/weight ratio Available Capacity
11
res+=int(capacity * (pair[1]/pair[0])) # Completely fill the bag
12
capacity=0
13
elif pair[0]<=capacity: # Take the whole object
14
res+=pair[1]
15
capacity-=pair[0]
16
print(res)
17
18
if __name__=="__main__":
19
fractional_knapsack()
20