Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. def branch_solve(items, max_cost):
  2. """
  3. Finds the optimal value possible from a combination of Items, given a cost constraint
  4. Parameters:
  5. items, a list of Items to consider
  6. max_cost, the cost/weight constraint
  7. Returns:
  8. the list of optimal Items and the total value attained
  9. """
  10.  
  11. # If there are no items left to choose from or no cost left to "spend"
  12. if not items or max_cost <= 0:
  13. return ([], 0) # Return an empty list and zero value
  14.  
  15. # Examine the branch that doesn't include taking this item
  16. without_item, without_item_val = branch_solve(items[1:], max_cost)
  17.  
  18. with_item_val = 0
  19. # If we can afford current item, examine branches that include it
  20. if items[0].cost <= max_cost: # Can afford current item
  21. # Explore options that include this item
  22. next_item = items[0]
  23. # Recursively examine all options with this item
  24. with_item, with_item_val = branch_solve(items[1:], max_cost - next_item.cost)
  25. with_item_val += next_item.value # Add value of next_item to total value
  26.  
  27. # Choose better "branch"; i.e. determine if we should include this item in the solution
  28. if with_item_val > without_item_val:
  29. # If value with item is higher, include the item
  30. result = (with_item + [next_item], with_item_val)
  31. else:
  32. # If value without item is higher, do not include the item
  33. result = (without_item, without_item_val)
  34.  
  35. # Return the list of items and the value they yield
  36. return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement