realsdx

knapsack2

Sep 9th, 2019
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.60 KB | None | 0 0
  1. def last(n):
  2.     return n[2]
  3. if __name__=="__main__":
  4.     print("Enter the no of items:")
  5.     n=int(input())
  6.     print("Enter capacity of knapsack:")
  7.     c=int(input())
  8.     l=[]
  9.     for i in range(n):
  10.         w,v=input().split()
  11.         w=int(w)
  12.         v=int(v)
  13.         tup=w,v,v/w
  14.         l.append(tup)
  15.     l.sort(key=lambda x:x[2])
  16.     prof=0
  17.     for i in range(n-1,-1,-1):
  18.         if l[i][0]<=c:
  19.             prof+=l[i][1]
  20.             print(l[i][1])
  21.             c-=l[i][0]
  22.         else:
  23.             prof+=c*l[i][2]
  24.             print(c,l[i][2])
  25.     print("The total Profit is ",prof)
Add Comment
Please, Sign In to add comment