Python最佳拟合算法

2024-09-27 00:23:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图为装箱设计一个最适合的算法。装箱问题:在给定容量的情况下,尽量减少用于包装物品的箱子数量。在

这个启发应该做的是

  1. 尽量将物品放在能容纳物品的最满的箱子里,也就是说,能留下最少空间的箱子

  2. 如果找不到箱子,启动一个新箱子。

为了写这个,我做了一个辅助卷。对于要放置的项目,将体积添加到每个箱子中。容量最大的箱子(这仍然可行)将得到该物品。我在Python中尝试了以下方法:

item = ['a', 'b', 'c', 'd', 'e']
volume = [9,5,6,7,2]
V = 15

class Bin(object):
 def __init__(self):
    self.items = []
    self.sumVolume = 0
    self.auxvolumeSpace = 0

 def add(self, item, volume):
    self.items.append(item)
    self.sumVolume += volume
    self.auxvolumeSpace = self.sumVolume

 def __str__(self):
    # Printable representation
    return 'Bin(TotalVolume=%d, products=%s)' % (self.sumVolume, str(self.items))

if __name__ == '__main__':

def packAndShow(volume, maxVolume):

    bins = pack(volume, maxVolume)

    print('Solution using', len(bins), 'bins:')
    for i in bins:
        print(i)
    print('The total amount of bins needed, using the Best fit Algorithm is: ',len(bins))


def auxiliaryspace(volume, maxVolume):
 bins = []
 maxvolumespace = -1

 for bin in bins:
    if bin.sumVolume + volume <= maxVolume:
        bin.auxvolumeSpace += volume
        if bin.auxvolumeSpace >= maxvolumespace:
            maxvolumespace = bin.auxvolumeSpace
 return maxvolumespace


def pack(volume, maxVolume):
 bins = []
 for i in range(len(volume)):
    mv = auxiliaryspace(volume[i], maxVolume) 
    for bin in bins:
        if mv > 0 and bin.auxvolumeSpace == mv:
            bin.add(item[i], volume[i])
            break
    else:
        bin = Bin()
        bin.add(item[i], volume[i])
        bins.append(bin)

return bins


packAndShow(volume, V)

问题是所有的东西都放在一个新的箱子里。结果如下:

^{pr2}$

我认为问题出在“辅助空间”部分。我认为返回的值(我想要的)不正确。。有人能帮忙吗?在


Tags: inselfforifbindefitem物品

热门问题