Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. # Solving the j-th Knapsack Problem using Dynamic Programming
  2.  
  3. # This is similar to the knapsack problem where we want to fill the container
  4. # with a maximum capacity L_j.
  5.  
  6. # Instead of maximizing the value, here we want to minimize the preference sum.
  7.  
  8. import sys
  9.  
  10. num_customers = 10
  11. preferences_j = []
  12. capacity_l_j = 100
  13. resource_requirement_j = []
  14.  
  15. # We want to find the assignments X_j.
  16.  
  17. memory = {}
  18. for i in range(n + 1):
  19. memory[i] = {}
  20.  
  21. # We can use the memory dictionary to store the results of the sub-problems
  22. # which we have already solved.
  23.  
  24. # We can use the DP formula :
  25. # memory[i][j] = For all j: min(memory[i-1][j], memory[i-1][j-r[i]] + preferences[i])
  26.  
  27. # Initialize the minimum preference sum to the maximum possible amount.
  28. for j in range(capacity_l_j + 1):
  29. memory[0][j] = sys.maxint
  30.  
  31. # Iterate through the customer list (1 to n) and possible resource usage sum (0 to capacity)
  32. for i in range(1, num_customers + 1):
  33. for j in range(0, capacity_l_j):
  34. if resource_requirement_j[i] <= j:
  35. memory[i][j] = memory[i - 1][j]
  36. else:
  37. memory[i][j] = min(memory[i][j], memory[i-1][j-resource_requirement_j[i] + preferences_j[i])
  38.  
  39. # The solution of the j-th knapsack problem can be obtained by consdiering all
  40. # the items (n) and the complete capacity of the container (capacity_l_j)
  41.  
  42. print memory[n][capacity_l_j]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement