|
|
发表于 2016-10-24 22:44:15
|
显示全部楼层
我写了个穷举法,对于你这种组合数量少的,还是很快的。
Max price 170, Optimization: (35, 30, 50, 10, 25)
[Finished in 0.2s]
- bag = {35:10,30:40,60:30,50:50,40:35,10:40,25:30}
- weight = [35,30,60,50,40,10,25]
- import itertools as it
- possible = []
- for i in range(3,6):
- com = it.combinations(weight,i)
- for eachcom in com:
- bagweight = 0
- for eachitem in eachcom:
- bagweight += eachitem
- if bagweight <= 150:
- possible.append(eachcom)
- prices = []
- for each in possible:
- bagprice = 0
- for e in each:
- bagprice += bag[e]
- prices.append(bagprice)
- maxprice = max(prices)
- maxcom = possible[prices.index(maxprice)]
- print ("Max price %d, " % maxprice, "Optimization: ", maxcom)
复制代码 |
|