example04.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """
  2. 贪婪法:在对问题求解时,总是做出在当前看来是最好的选择,
  3. 不追求最优解,快速找到满意解。
  4. """
  5. class Thing(object):
  6. """物品"""
  7. def __init__(self, name, price, weight):
  8. self.name = name
  9. self.price = price
  10. self.weight = weight
  11. @property
  12. def value(self):
  13. """价格重量比"""
  14. return self.price / self.weight
  15. def input_thing():
  16. """输入物品信息"""
  17. name_str, price_str, weight_str = input().split()
  18. return name_str, int(price_str), int(weight_str)
  19. def main():
  20. """主函数"""
  21. max_weight, num_of_things = map(int, input().split())
  22. all_things = []
  23. for _ in range(num_of_things):
  24. all_things.append(Thing(*input_thing()))
  25. all_things.sort(key=lambda x: x.value, reverse=True)
  26. total_weight = 0
  27. total_price = 0
  28. for thing in all_things:
  29. if total_weight + thing.weight <= max_weight:
  30. print(f'小偷拿走了{thing.name}')
  31. total_weight += thing.weight
  32. total_price += thing.price
  33. print(f'总价值: {total_price}美元')
  34. if __name__ == '__main__':
  35. main()