Lecture 2 Decision Trees and Dynamic Programming
Brute Force Algorithms
暴力算法,穷举法
Decision Tree
class Food(object):
def __init__(self, n, v, w):
self.name = n
self.value = v
self.calories = w
def getValue(self):
return self.value
def getCost(self):
return self.calories
def density(self):
return self.getValue() / self.getCost()
def __str__(self):
return self.name + ': <' + str(self.value) + ', ' + str(self.calories) + '>'
def buildMenu(names, values, calories):
"""names, values, calories lists of same length.
name a list of strings
values and calories lists of numbers
return list of Foods"""
menu = []
for i in range(len(values)):
menu.append(Food(names[i], values[i], calories[i]))
return menu
def greedy(items, maxCost, keyFunction):
"""assumes items a list, maxCost >= 0,
keyFunction maps elements of items to numbers"""
itemsCopy = sorted(items, key = keyFunction, reverse = True) # 从高到低
result = []
totalValue, totalCost = 0.0, 0.0
for i in range(len(items)):
if (totalCost + itemsCopy[i].getCost()) <= maxCost: # 检查是否还有空间放新东西
result.append(itemsCopy[i])
totalCost += itemsCopy[i].getCost()
totalValue += itemsCopy[i].getValue()
return (result, totalValue)
def testGreedy(items, constraint, keyFunction):
taken, val = greedy(items, constraint, keyFunction)
print('Total value of items taken = ', val)
for item in taken:
print(' ', item)
def testGreedys(foods, maxUnits):
pr