Ai
1 Star 0 Fork 2

open/Python-100-Days

forked from 阿甘/Python-100-Days 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
example04.py 1.13 KB
一键复制 编辑 原始数据 按行查看 历史
jackfrued 提交于 2019-02-13 07:38 +08:00 . 更新了文档和目录结构
"""
贪婪法:在对问题求解时,总是做出在当前看来是最好的选择,
不追求最优解,快速找到满意解。
"""
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()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
HTML
1
https://gitee.com/netb/Python-100-Days.git
git@gitee.com:netb/Python-100-Days.git
netb
Python-100-Days
Python-100-Days
master

搜索帮助