Advertisement
Gologo

backpack

Oct 21st, 2019
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. def backpack_bottom_up(values,weights,max_weight_constraint,cache):
  2.     for total_items in range(len(values)+1):
  3.         for max_weight in range(max_weight_constraint+1):
  4.             current_item = total_items - 1
  5.             if total_items == 0 and max_weight == 0:
  6.                 cache[total_items][max_weight] = 0
  7.             elif weights[current_item] > max_weight:
  8.                 cache[total_items][max_weight] = cache[total_items - 1][max_weight]
  9.             else:
  10.                 with_item = values[current_item] + cache[total_items - 1][max_weight - weights[current_item]]
  11.                 without_item = cache[total_items - 1][max_weight]
  12.                
  13.                 cache[total_items][max_weight] = max(with_item, without_item)
  14.    
  15.     return cache[len(values)][max_weight_constraint]
  16.    
  17. def print_cache(cache):
  18.     for row in cache[:-1]:
  19.         print(row)
  20.  
  21. values = [40,20,60,100]
  22. weight = [1,2,3,4]
  23.  
  24. max_weight = 5
  25.  
  26. cache = [[0 for c in range(max_weight+1)] for c in range(len(weight)+2)]
  27.  
  28. print(backpack_bottom_up(values, weight, max_weight, cache))
  29.  
  30. print_cache(cache)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement