“搜索树算法中令人困惑的语法”

2024-04-19 18:31:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在从MITx拿6.00.2x,有一行搜索树算法让我困惑,有人能帮我吗?你知道吗

val, taken = maxVal(foods, maxUnits)

这种语法对我没有意义。maxVal是一个函数,因此foodsmaxUnits可能是输入。但是valtaken是什么,这条线做什么?代码中没有用这些名称实例化的变量,所以我不确定它们是什么(这行语法的意思)。你知道吗

注:完整代码如下。上述语法出现在函数testMaxVal的第3行。foods是一个由1)食物、2)价值观和3)卡路里组成的列表。你知道吗

def maxVal(toConsider, avail):
    """Assumes toConsider a list of items, avail a weight
       Returns a tuple of the total value of a solution to the
         0/1 knapsack problem and the items of that solution"""
    if toConsider == [] or avail == 0:
        result = (0, ())
    elif toConsider[0].getCost() > avail:
        #Explore right branch only
        result = maxVal(toConsider[1:], avail)
    else:
        nextItem = toConsider[0]
        #Explore left branch
        withVal, withToTake = maxVal(toConsider[1:],
                                     avail - nextItem.getCost())
        withVal += nextItem.getValue()
        #Explore right branch
        withoutVal, withoutToTake = maxVal(toConsider[1:], avail)
        #Choose better branch
        if withVal > withoutVal:
            result = (withVal, withToTake + (nextItem,))
        else:
            result = (withoutVal, withoutToTake)
    return result

def testMaxVal(foods, maxUnits, printItems = True):
    print('Use search tree to allocate', maxUnits,
          'calories')
    val, taken = maxVal(foods, maxUnits)
    print('Total value of items taken =', val)
    if printItems:
        for item in taken:
            print('   ', item)

testMaxVal(foods, 750)

Tags: ofbranch语法itemsvalresulttakenfoods
3条回答

函数maxVal返回一个tuple。可以从python中的函数返回多个值,格式为tuple。你知道吗

示例:

def connect():
    connection = _connect()
    message = "Connected"
    if not connection:
        message = "Not connected"
    return connection, message

connection, message = connect()

如您所见,maxVal可以同时返回两个输出,就像在行中一样:

result = (withoutVal, withoutToTake)

在两个变量val中恢复这两个输出

val, taken = maxVal(foods, maxUnits)

maxVal返回一对。
您可以通过同时将任何元组的元素分配给适当数量的变量来“解构”任何元组。你知道吗

示例:

>>> a,b,c = (1,2, "hello")
>>> a
1
>>> b
2
>>> c
'hello'

相关问题 更多 >