Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def greedy_solve(items, max_cost, key_function):
- """
- Finds local maximal value from a combination of Items,
- given a cost constraint and metric (e.g. value, cost, density)
- Parameters:
- items, a list of Items to consider
- max_cost, the cost/weight constraint
- key_function, the metric to determine most favorable items
- Returns:
- the list of Items to take and the total value attained
- """
- # Make a copy of items, sorted by key (e.g. cost, density, value)
- sorted_items = sorted(items, key=key_function, reverse=True)
- # Make an empty list to hold results
- result = []
- # Initialize total value and total cost at 0
- total_value, total_cost = 0, 0
- # Iterate through sorted items
- for item in sorted_items:
- # If we can "afford" the next item, add it to the list
- if (total_cost + item.cost) <= max_cost:
- result.append(item)
- total_cost += item.cost
- total_value += item.value
- # Return the result and total value of it
- return result, total_value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement