nathanwailes

Knapsack - Unbounded - DP - v1

Jun 15th, 2024
462
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. """
  2. """
  3. def unbounded_knapsack(capacity, weights, values, index, memo):
  4.     # base case:
  5.     if index == 0:
  6.         return (capacity // weights[0]) * values[0]
  7.    
  8.     # Return previously calculated value if available.
  9.     if memo[index][capacity] != -1:
  10.         return memo[index][capacity]
  11.    
  12.     # Case 1: Do not take the current item.
  13.     exclude = unbounded_knapsack(capacity, weights, values, index - 1, memo)
  14.    
  15.     # Case 2: Take the current item if its weight is less than or equal to capacity.
  16.     include = float('-inf')
  17.     if weights[index] <= capacity:
  18.         include = values[index] + unbounded_knapsack(capacity - weights[index], weights, values, index, memo)
  19.    
  20.     # Store the result in the memoization table.
  21.     memo[index][capacity] = max(include, exclude)
  22.     return memo[index][capacity]
  23.  
  24. capacity = 100
  25. values = [10, 30, 20]
  26. weights = [5, 10, 15]
  27. num_items = len(values)
  28. memo = [[-1 for _ in range(capacity + 1)] for _ in range(num_items)]
  29. print(unbounded_knapsack(capacity, weights, values, num_items - 1, memo))
  30.  
Advertisement
Add Comment
Please, Sign In to add comment