Guest User

Untitled

a guest
Feb 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. # Knapsack problem
  2.  
  3. class Item(object):
  4.  
  5. def __init__(self, value, weight):
  6. self.value, self.weight = value, weight
  7.  
  8. items = [
  9. None,
  10. Item(4, 2),
  11. Item(5, 2),
  12. Item(2, 1),
  13. Item(8, 3),
  14. ]
  15.  
  16. # Weight of the knapsack
  17. N = 5
  18.  
  19. cells = [[0] * (N+1) for i in xrange(len(items))]
  20. for i, item in enumerate(items):
  21. for w in xrange(N+1):
  22. if item is None:
  23. cells[i][w] = 0
  24. continue
  25.  
  26. c1, c2 = 0, 0
  27. if item.weight <= w:
  28. c1 = item.value
  29. if i > 0:
  30. c1 += cells[i - 1][w - item.weight]
  31. if i > 0:
  32. c2 = cells[i - 1][w]
  33. cells[i][w] = max(c1, c2)
  34.  
  35. print "\n".join(["\t".join(str(i) for i in inter) for inter in cells])
  36.  
  37. print "Max = %d" % cells[len(items) - 1][N]
  38. w = N
  39. for i, item in reversed(list(enumerate(items))):
  40. if item is None:
  41. continue
  42. if cells[i][w] > cells[i - 1][w]:
  43. print " Selected: (%d, %d)" % (item.value, item.weight)
  44. w -= item.weight
Add Comment
Please, Sign In to add comment