Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. def greedy_solve(items, max_cost, key_function):
  2. """
  3. Finds local maximal value from a combination of Items,
  4. given a cost constraint and metric (e.g. value, cost, density)
  5. Parameters:
  6. items, a list of Items to consider
  7. max_cost, the cost/weight constraint
  8. key_function, the metric to determine most favorable items
  9. Returns:
  10. the list of Items to take and the total value attained
  11. """
  12.  
  13. # Make a copy of items, sorted by key (e.g. cost, density, value)
  14. sorted_items = sorted(items, key=key_function, reverse=True)
  15.  
  16. # Make an empty list to hold results
  17. result = []
  18.  
  19. # Initialize total value and total cost at 0
  20. total_value, total_cost = 0, 0
  21.  
  22. # Iterate through sorted items
  23. for item in sorted_items:
  24. # If we can "afford" the next item, add it to the list
  25. if (total_cost + item.cost) <= max_cost:
  26. result.append(item)
  27. total_cost += item.cost
  28. total_value += item.value
  29.  
  30. # Return the result and total value of it
  31. return result, total_value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement