背包问题的贪婪算法,以Python中的Robbery为例

Unfortunately, a thief targeted a house and there he found lots of items to steal. Now each item has its value (quantified) and volume. Now the thief has to decide which item to take so that he can have maximum value within a constrained volume. This is an optimization problem in which we have to optimize the overall quantified value by selecting the best items to steal within his bag. The bag can have a maximum volume of 54 Liters.

不幸的是,一个小偷瞄准了一所房子,在那里他发现很多东西要偷。 现在,每个项目都有其值(量化)和数量。 现在,小偷必须决定拿走哪个物品,以便他可以在受限的体积内获得最大价值。 这是一个优化问题,我们必须通过选择最好的物品来窃取他的包,以优化整体量化值。 袋子的最大容量为54升。

Program:

程序:

# Greedy Algorithm for a Robbery

# Defined a class for items, with 
# its name, value and volume 
# We have to optimise the selection 
# with maximum value within 1000 unit volume space
class itmcls(object):
    def __init__(self, name, val, vol):
        self.name = name
        self.val = val
        self.vol = vol
        
    def getvalue(self):
        return self.val
    
    def getvol(self):
        return self.vol
    
    def density(self):
        return (self.val)/(self.vol)
    
    def __str__(self):
        return self.name 
  
# Defining a function for building a bag 
# which generates list of itmcls    
def buildbag(names, values, volumes):
    bag = []
    for i in range(len(names)):
        bag.append(itmcls(names[i], values[i], volumes[i]))
    return bag

# Implementation of greedy algorithm to choose 
# one of the optimum choice
def greedy(items, maxvol, keyfunction):
    itemscopy = sorted(items, key = keyfunction, reverse = True)
    
    result = []
    totalval = 0 
    totalvol = 0
    
    for i in range(len(items)):
        if (totalvol + itemscopy[i].getvol() <= maxvol):
            result.append(itemscopy[i])
            totalval = totalval + itemscopy[i].getvalue()
            totalvol = totalvol + itemscopy[i].getvol()
            
    return (result, totalval)

# Main Function
itemlist = ['phone', 'laptop', 'applemacbook', 'ipad', 'Money', 'goldcoin', 'coldrink', 'bowl']
values = [89,90,95,78,97,84,32,45]
volumes = [6,8,15,17,12,18,8,9]
itemlistt = buildbag(itemlist, values, volumes)
maxvol = 54

taken, totvalue = greedy(itemlistt, maxvol, itmcls.density)

print('Total vaule taken : ', totvalue)

# Printing the list of items slected for 
# optimum value in terms of density
for i in range(len(taken)):
    print('  ', taken[i])

Output

输出量

Total vaule taken :  416
   phone
   laptop
   Money
   applemacbook
   bowl


翻译自: https://www.includehelp.com/python/greedy-algorithm-for-a-knapsack-problem-with-the-example-of-robbery.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值