Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. # input
  2. # values stored in array v
  3. # wighets stored in array wt
  4. #length of array n
  5. # knapsack capcity stored in w
  6.  
  7. #A naive recursive implementation of 0-1 Knapsack Problem
  8. # Returns the maximum value that can be put in a knapsack of
  9. # capacity W
  10. def knapSack(w, wt, v, n):
  11.  
  12. # base case
  13.  
  14. if n == 0 or w == 0:
  15. return 0
  16.  
  17. # if weight of the nth item is more than knapsack of capcity
  18. # w then this item cannot be included in the optimal solution
  19. if(wt[n-1] > w):
  20. return knapSack(w, wt, v, n-1)
  21.  
  22. # return the maximum of two cases
  23. # (1) nth item included
  24. # (2) not included
  25.  
  26. else:
  27. return max(v[n-1] + knapSack(w-wt[n-1], wt , v, n-1), knapSack(w, wt, v, n-1))
  28.  
  29. # end of function knapSack
  30.  
  31. v = [100, 40, 70]
  32. wt = [4, 2, 3]
  33. w = 5
  34. n = len(v)
  35.  
  36. print knapSack(w, wt, v, n)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement