MITx - 6.00.2x 笔记(Unit1 Lecture 2 Decision Trees and Dynamic Programming)

本文主要介绍了MITx 6.00.2x课程中的决策树和动态规划概念。讨论了暴力算法在解决背包问题时的2^N种可能性,以及如何通过按位运算符进行列举。同时,回顾了递归斐波那契数列的效率问题,并提出使用字典存储已计算过的斐波那契数以提高效率。最后,简要总结了动态规划的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Lecture 2 Decision Trees and Dynamic Programming

Brute Force Algorithms

暴力算法,穷举法

Decision Tree

DecisionTree

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值