栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

打包算法的Python实现

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

打包算法的Python实现

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 binsif __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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485630.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号