/
githubmirror
/
Python-100-Days
Обзор
Документация
Войти
/
githubmirror
/
Python-100-Days
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
Day31-35/code/example04.py
43 строки
1 KB
jackfrued
调整了目录结构
30 янв 2025, 18:25
30 янв 2025, 18:25
3dc3938
Код
Авторство
О чём код?
""" 贪婪法:在对问题求解时,总是做出在当前看来是最好的选择, 不追求最优解,快速找到满意解。 """ class Thing(object): """物品""" def __init__(self, name, price, weight): self.name = name self.price = price self.weight = weight @property def value(self): """价格重量比""" return self.price / self.weight def input_thing(): """输入物品信息""" name_str, price_str, weight_str = input().split() return name_str, int(price_str), int(weight_str) def main(): """主函数""" max_weight, num_of_things = map(int, input().split()) all_things = [] for _ in range(num_of_things): all_things.append(Thing(*input_thing())) all_things.sort(key=lambda x: x.value, reverse=True) total_weight = 0 total_price = 0 for thing in all_things: if total_weight + thing.weight <= max_weight: print(f'小偷拿走了{thing.name}') total_weight += thing.weight total_price += thing.price print(f'总价值: {total_price}美元') if __name__ == '__main__': main()