使用python 解决背包问题,代码还可以进一步优化,先粘贴出来,以作以后处理
#coding:utf-8
#存放多种组合,key为价格,value为good_store实例
combination = {}
class goods(object):
'''
#物品类
#三个属性,价格,体积,物品名称
'''
def __init__(self, name, price, volume):
self.price = price
self.volume = volume
self.name = name
class good_store(object):
'''
#一种物品组合存储容器类
#四个属性,容器内物品总体积,容器内物品总价值,容器内物品,容器最大容积
'''
def __init__(self, max_v):
self.volume = 0
self.price = 0
self.goods = []
self.max_v = max_v
def put(self, goods):
'''
#存放物品,存放成功返回True,否则返回False
'''
if self.volume+goods.volume > self.max_v:
return False
self.goods.append(goods)
self.volume += goods.volume
self.price += goods.price
return True
def find_combination(dst, store, bag_volume ):
'''
#递归完成物品组合放置
#
'''
global combination
for i in dst:
if store.put(i):
new_dst = [j for j in dst if j != i]
if not find_combination(new_dst,store, bag_volume):
combination[store.price] = store
store = good_store(bag_volume)
else:
continue
return False
if __name__ == "__main__":
#global combination
bag_volume = 40
aa = goods('aa', 10, 5)
bb = goods('bb', 20, 30)
cc = goods('cc', 15, 10)
dd = goods('dd', 6, 2)
ee = goods('ee', 11, 11)
ff = goods('ff', 25, 11)
dst = [aa, bb, cc, dd, ee, ff]
st = good_store(bag_volume)
find_combination(dst, st, bag_volume)
print(max(combination.keys()))
print(combination[max(combination.keys())] )