CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

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