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

15 篇文章 0 订阅
3 篇文章 0 订阅

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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值