Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def branch_solve(items, max_cost):
- """
- Finds the optimal value possible from a combination of Items, given a cost constraint
- Parameters:
- items, a list of Items to consider
- max_cost, the cost/weight constraint
- Returns:
- the list of optimal Items and the total value attained
- """
- # If there are no items left to choose from or no cost left to "spend"
- if not items or max_cost <= 0:
- return ([], 0) # Return an empty list and zero value
- # Examine the branch that doesn't include taking this item
- without_item, without_item_val = branch_solve(items[1:], max_cost)
- with_item_val = 0
- # If we can afford current item, examine branches that include it
- if items[0].cost <= max_cost: # Can afford current item
- # Explore options that include this item
- next_item = items[0]
- # Recursively examine all options with this item
- with_item, with_item_val = branch_solve(items[1:], max_cost - next_item.cost)
- with_item_val += next_item.value # Add value of next_item to total value
- # Choose better "branch"; i.e. determine if we should include this item in the solution
- if with_item_val > without_item_val:
- # If value with item is higher, include the item
- result = (with_item + [next_item], with_item_val)
- else:
- # If value without item is higher, do not include the item
- result = (without_item, without_item_val)
- # Return the list of items and the value they yield
- return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement