DP(Dynamic Programming) demo: optimal substructure(recursion) + overlapping structure(memo)
2015-05-29 09:02
741 查看
#quote from 'introduction to computation and programming using python, # revised edition, MIT' class Item(object): def __init__(self, n, v, w): self.name = n self.value = float(v) self.weight = float(w) def getName(self): return self.name def getValue(self): return self.value def getWeight(self): return self.weight def __str__(self): result = '<' + self.name + ', ' + str(self.value)\ + ', ' + str(self.weight) + '>' return result def fastMaxVal(toConsider, avail, memo = {}): """Asumes toConsider a list of items, avail a weight memo used only by recursive calls Returns a tuple of the total weight of a solution to the 0/1 knapsack problem and the items of that solution""" if (len(toConsider), avail) in memo: result = memo[(len(toConsider), avail)] elif toConsider == [] or avail == 0: result = (0, ()) elif toConsider[0].getWeight() > avail: #Explore right branch only result = fastMaxVal(toConsider[1:], avail, memo) else: nextItem = toConsider[0] #Explore left branch withVal, withToTake =\ fastMaxVal(toConsider[1:], avail - nextItem.getWeight(), memo) withVal += nextItem.getValue() #Explore right branch withoutVal, withoutToTake = fastMaxVal(toConsider[1:], avail, memo) #Choose better branch if withVal > withoutVal: result = (withVal, withToTake + (nextItem,)) else: result = (withoutVal, withoutToTake) memo[(len(toConsider), avail)] = result return result def smallTest(): names = ['a', 'b', 'c', 'd'] vals = [6, 7, 8, 9] weights = [3, 3, 2, 5] Items = [] for i in range(len(vals)): Items.append(Item(names[i], vals[i], weights[i])) val, taken = fastMaxVal(Items, 5) for item in taken: print item print 'Total value of items taken =', val
相关文章推荐
- IOS CoreText --- 基本用法
- Android ----Intent 的各种打开文件 doc word
- 从android到ios
- ios 手势
- 【swift】15-0528 函数参数
- IOS 开发学习28 NSArray 基本用法
- Android Studio 快捷键
- 一---Android-SDK系列文章(2) ---java(class,package,import)
- android 镜像汇总
- android启动之子系统切换
- 开源 java CMS - FreeCMS2.3 移动app生成站点列表数据
- android Universal-Image-Loader框架学习(上)
- memorization(overlapping subproblems) demo
- 正确使用Android性能分析工具——TraceView
- IOS开发学习27 ObjectC 自带json解析方法的使用
- Android:有份额无利润 腹背受敌
- Android M帮助文档下载
- Swift学习笔记-字典Dictionary
- Opencv2 computer vision application programming cookbook<七>
- iOS 逆向之ARM汇编