Skip to content

Commit 94324e9

Browse files
Vishu26harshildarji
authored andcommitted
Create FractionalKnapsack.py (TheAlgorithms#438)
1 parent 81dc87a commit 94324e9

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed
+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from itertools import accumulate
2+
from bisect import bisect
3+
4+
def fracKnapsack(vl, wt, W, n):
5+
6+
r = list(sorted(zip(vl,wt), key=lambda x:x[0]/x[1],reverse=True))
7+
vl , wt = [i[0] for i in r],[i[1] for i in r]
8+
acc=list(accumulate(wt))
9+
k = bisect(acc,W)
10+
return 0 if k == 0 else sum(vl[:k])+(W-acc[k-1])*(vl[k])/(wt[k]) if k!=n else sum(vl[:k])
11+
12+
print("%.0f"%fracKnapsack([60, 100, 120],[10, 20, 30],50,3))

0 commit comments

Comments
 (0)