MITx - 6.00.2x 笔记(Unit1 Lecture 1 Knapsack Problem)

Introduction to Computational Thinking and Data Science

Practice, practice, and practice !

  • Optimization models 优化模型
  • Statistical models 统计模型
  • Simulation models 仿真模型

Lecture 1 优化和背包问题(Knapsack Problem)

  • 优化模型的典型特征
    • 需要达到最大化或最小化的函数对象
    • 一些必须遵循的限制条件
    • 有时我们找到的是足够好的解决办法,而不一定是最优解

0/1 Knapsack Problem

Knapsack Problem 1
Knapsack Problem 2
Knapsack Problem 3

Greedy Algorithms

遇到很难的问题,我们可以做什么?
Hard Problem
例题:假设希望摄入的热量不超过800卡路里,如何根据食物热量表选择食物?
Food Table

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(name[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)

BigO·

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):
    print('Use greedy by value to allocate', maxUnits, 'calories')
    testGreedy(foods, maxUnits, Food.getValue)

    print('\nUse greedy by cost to allocate', maxUnits, 'calories')
    testGreedy(foods, maxUnits, 
                       lambda x: 1/Food.getCost(x))

    print('\nUse greedy by density to allocate', maxUnits, 'calories')
    testGreedy(foods, maxUnits, Food.density)


names = ['wine', 'beer', 'pizza', 'burger', 'fries', 'cola', 'apple', 'donut', 'cake']
values = [89, 90, 95, 100, 90, 79, 50, 10]
calories = [123, 154, 258, 354, 365, 150, 95, 195]
foods = buildMenu(names, values, calories) 
testGreedys(foods, 750)
# Out
Use greedy by value to allocate 750 calories
Total value of items taken =  284.0
     burger: <100, 354>
     pizza: <95, 258>
     wine: <89, 123>

Use greedy by cost to allocate 750 calories
Total value of items taken =  318.0
     apple: <50, 95>
     wine: <89, 123>
     cola: <79, 150>
     beer: <90, 154>
     donut: <10, 195>

Use greedy by density to allocate 750 calories
Total value of items taken =  318.0
     wine: <89, 123>
     beer: <90, 154>
     cola: <79, 150>
     apple: <50, 95>
     donut: <10, 195>
posted @ 2018-03-04 00:00  huidan  阅读(430)  评论(0编辑  收藏  举报