Ada 8

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Practical-8

Aim:- Algorithm and Implementation of Knapsack


Problem(using Greedy Algorithms).
Algorithm:-
1. W and item have value Vi and weight Wi.
2. Rank item by value/weight ratio: Vi/Wi.
3. Thus : Vi/Wi= Vj/Wj for all i<=Wj.
4. Consider items in order of descending ratio.
5. Take as much of each item is possible.
6. Assume value and weight arrays are
sorted by Vi<=Wi fractional knapsack (V,w,W)
7. Load:=0
8. i:=1
9. while load<w and i<=n loop
10. if
11. wi <=W –loop then
12. take all of item i
13. else
14. take (W-load)/wi of item i
15. end if
16. Add weight of what was taken to load.
17. i:i+1
18. end loop
19. return loop

Program:-
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))

Output:-
230
Time Complexity:-
The time complexity of the fractional knapsack problem
is O(NlogN).

You might also like