gpt4 book ai didi

打包算法的Python实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:23:37 27 4
gpt4 key购买 nike

对于我正在处理的应用程序,我需要类似用 Python 实现的打包算法的东西 see here for more details .基本思想是我有 n 个不同大小的对象,我需要将它们放入 n 个箱子中,其中箱子的数量以及对象和箱子的大小都是有限的是固定的。对象/容器可以是 1d 或 2d,有兴趣查看两者。 (我认为 3d 对象可能比我需要的更多。)

我知道有多种算法可以解决这个问题,例如最佳拟合递减和首次拟合递减,但我希望可能有 Python(或 PHP/C++/Java,我真的没那么挑剔)。有什么想法吗?

最佳答案

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)

关于打包算法的Python实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23305342/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com