包装算法的Python实现

2024-05-09 06:53:26 发布

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

对于我正在开发的应用程序,我需要类似于用Pythonsee here for more details实现的打包算法。基本思想是我有大小不一的n对象需要放入n容器,其中容器的数量是有限的,对象和容器的大小都是固定的。对象/容器可以是1d或2d,希望看到两者。(我认为3d对象可能比我需要的更多。)

我知道有很多算法解决了这个问题,比如最佳拟合减少和第一拟合减少,但是我希望在Python中可以实现(或者PHP/C++ +java,实际上我不是那么挑剔)。有什么想法吗?


Tags: 对象算法应用程序for数量heremorejava
1条回答
网友
1楼 · 发布于 2024-05-09 06:53:26

https://bitbucket.org/kent37/python-tutor-samples/src/f657aeba5328/BinPacking.py

""" Partition a list into sublists whose sums don't exceed a maximum 
    using a First Fit Decreasing algorithm. See
    http://www.ams.org/new-in-math/cover/bins1.html
    for a simple description of the method.
"""


class Bin(object):
    """ Container for items that keeps a running sum """
    def __init__(self):
        self.items = []
        self.sum = 0

    def append(self, item):
        self.items.append(item)
        self.sum += item

    def __str__(self):
        """ Printable representation """
        return 'Bin(sum=%d, items=%s)' % (self.sum, str(self.items))


def pack(values, maxValue):
    values = sorted(values, reverse=True)
    bins = []

    for item in values:
        # Try to fit item into a bin
        for bin in bins:
            if bin.sum + item <= maxValue:
                #print 'Adding', item, 'to', bin
                bin.append(item)
                break
        else:
            # item didn't fit into any bin, start a new bin
            #print 'Making new bin for', item
            bin = Bin()
            bin.append(item)
            bins.append(bin)

    return bins


if __name__ == '__main__':
    import random

    def packAndShow(aList, maxValue):
        """ Pack a list into bins and show the result """
        print 'List with sum', sum(aList), 'requires at least', (sum(aList)+maxValue-1)/maxValue, 'bins'

        bins = pack(aList, maxValue)

        print 'Solution using', len(bins), 'bins:'
        for bin in bins:
            print bin

        print


    aList = [10,9,8,7,6,5,4,3,2,1]
    packAndShow(aList, 11)

    aList = [ random.randint(1, 11) for i in range(100) ]
    packAndShow(aList, 11)

相关问题 更多 >