Guest User

Untitled

a guest
May 25th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.67 KB | None | 0 0
  1. def knapsack(weights, values, weight_limit):
  2. best_values = [0] * (weight_limit + 1)
  3. for w in range(1, weight_limit + 1):
  4. best_val_for_weight = 0
  5. for i in range(len(weights)):
  6. if weights[i] <= w:
  7. prev_weight = w - weights[i]
  8. possible_best_weight = best_values[prev_weight] + values[i]
  9. if possible_best_weight > best_val_for_weight:
  10. best_val_for_weight = possible_best_weight
  11. best_values[w] = best_val_for_weight
  12. print('', w,':', best_values[w])
  13.  
  14.  
  15. itemWeights = [2, 4, 5]
  16. itemValues = [3, 6, 7]
  17. bagWeightLimit = 6
  18. knapsack(itemWeights, itemValues, bagWeightLimit)
Add Comment
Please, Sign In to add comment