use decision tree to solve 0-1 knapsack problem // optimal substructure
来源:互联网 发布:手机淘宝联盟登录失效 编辑:程序博客网 时间:2024/06/06 20:23
#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 maxVal(toConsider, avail): """Assumes toConsider a list of items, avail a weigth Returns a tuple of total weight of a solution to the 0/1 knapsack problem and the items of that solution""" #simple case: no item left or no space left if toConsider == [] or avail == 0: result = (0, ()) #recursive decomposition #the item is too big elif toConsider[0].getWeight() > avail: #Explore right branch only result = maxVal(toConsider[1:], avail) else: nextItem = toConsider[0] #Explore left branch: take withVal, withToTake = maxVal(toConsider[1:], avail - nextItem.getWeight()) withVal += nextItem.getValue() #Explore right branch: not take withoutVal, withoutToTake = maxVal(toConsider[1:], avail) #Choose better branch if withVal > withoutVal: result = (withVal, withToTake + (nextItem,)) else: result = (withoutVal, withoutToTake) 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 = maxVal(Items, 5) for item in taken: print item print 'Total value of items taken =', val
0 0
- use decision tree to solve 0-1 knapsack problem // optimal substructure
- brute force method for optimal solution(0-1 knapsack problem)
- Solution to 0–1 Knapsack Problem
- 0-1 knapsack problem
- 0-1 Knapsack Problem
- Use EMC powermt to solve PowerPath Problem
- Use Y method to solve Problem X
- [DP] 0-1 Knapsack Problem
- 【DP】 0/1 knapsack problem (single copy)
- 0-1背包问题(knapsack problem)
- Geeks面试题:0-1 Knapsack Problem
- FZU 2214 Knapsack problem (0/1背包)
- DP10 0-1背包问题 0-1 Knapsack Problem @geeksforgeeks
- 0-1背包问题 DPL_1_B- 0-1 Knapsack Problem
- how to solve aliasing problem
- Optimal Substructure DEMO(without memorization: overlapping subproblems)
- 最优子结构(Optimal Substructure)
- 最优子结构(optimal substructure)
- Cocoa小例子
- Android Studio 快捷键
- leetcode 215: Kth Largest Element in an Array
- VS2010 C++ MFC框架学习笔记1 - 创建一个简单的加法计算器(1)
- verilog实现的毫秒级计时器
- use decision tree to solve 0-1 knapsack problem // optimal substructure
- Linux如何查看进程、杀死进程、启动进程等常用命令
- vxworks 使用nand flash时候SIGSEGV解决
- curl并发例子
- IOS 开发学习28 NSArray 基本用法
- Algorithm: Find the maximum
- 【黑马程序员】------java基础语法--关键字、变量、常量、运算符
- HTML5和HTML属性及元素整理
- sql server 2008下可以调试T-SQL语句