贪心算法
1、贪心算法介绍
2、贪心算法的基本思想
3、解决会议安排问题
#会议类 class meet: num=0 begin=0 end=0 #所有会议 meets=[] #初始化会议列表 m=meet() m.num=1 m.begin=8 m.end=10 meets.append(m) m=meet() m.num=2 m.begin=9 m.end=11 meets.append(m) m=meet() m.num=3 m.begin=10 m.end=15 meets.append(m) m=meet() m.num=4 m.begin=11 m.end=14 meets.append(m) m=meet() m.num=5 m.begin=13 m.end=16 meets.append(m) m=meet() m.num=6 m.begin=14 m.end=17 meets.append(m) m=meet() m.num=7 m.begin=15 m.end=17 meets.append(m) m=meet() m.num=8 m.begin=17 m.end=18 meets.append(m) m=meet() m.num=9 m.begin=18 m.end=20 meets.append(m) m=meet() m.num=10 m.begin=16 m.end=19 meets.append(m) import operator selectmeets=[] #选择参与的会议 def selectmeet(meetlist): cmpfun = operator.attrgetter('end') #按照end进行排序 meetlist.sort(key = cmpfun) selectmeets.append(meetlist[0]) #先选第一个会议 endtime=meetlist[0].end #会议结束时间 for i in range(1,len(meetlist)): if endtime<=meetlist[i].begin: #如果结束时间小于该会议的起始时间 selectmeets.append(meetlist[i]) endtime=meetlist[i].end selectmeet(meets) for obj in selectmeets: print(obj.num) '''打印结果为: 1 4 6 8 9 '''
4、解决背包问题
#商品类 class good: name="" #商品名 weight=0 #重量 price=0 #价格 p=0 #性价比 goods=[] g=good() g.name="手表" g.weight=2 g.price=85 g.p=g.price/g.weight goods.append(g) g=good() g.name="剃须刀" g.weight=3 g.price=60 g.p=g.price/g.weight goods.append(g) g=good() g.name="西瓜" g.weight=5 g.price=10 g.p=g.price/g.weight goods.append(g) g=good() g.name="篮球" g.weight=1.5 g.price=30 g.p=g.price/g.weight goods.append(g) g=good() g.name="可乐" g.weight=1 g.price=3.5 g.p=g.price/g.weight goods.append(g) g=good() g.name="香烟" g.weight=2.5 g.price=75 g.p=g.price/g.weight goods.append(g) g=good() g.name="茅台" g.weight=1.2 g.price=240 g.p=g.price/g.weight goods.append(g) g=good() g.name="烤鸡" g.weight=2.2 g.price=22 g.p=g.price/g.weight goods.append(g) g=good() g.name="相机" g.weight=2 g.price=2000 g.p=g.price/g.weight goods.append(g) g=good() g.name="袜子" g.weight=1 g.price=12 g.p=g.price/g.weight goods.append(g) import operator selectgoods=[] #挑选的商品 def selectgood(goodlist): cmpfun=operator.attrgetter('p') #按性价比排序 goodlist.sort(key=cmpfun,reverse=True) residueweight=12 #背包剩余承重空间 for obj in goodlist: if residueweight>=obj.weight: #如果总重小于背包承重 selectgoods.append(obj) residueweight=residueweight-obj.weight selectgood(goods) for obj in selectgoods: print(obj.name) '''打印结果为: 相机 茅台 手表 香烟 剃须刀 袜子 '''