我现在从MITx拿6.00.2x,有一行搜索树算法让我困惑,有人能帮我吗?你知道吗
val, taken = maxVal(foods, maxUnits)
这种语法对我没有意义。maxVal
是一个函数,因此foods
和maxUnits
可能是输入。但是val
和taken
是什么,这条线做什么?代码中没有用这些名称实例化的变量,所以我不确定它们是什么(这行语法的意思)。你知道吗
注:完整代码如下。上述语法出现在函数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)
函数
maxVal
返回一个tuple
。可以从python中的函数返回多个值,格式为tuple
。你知道吗示例:
如您所见,maxVal可以同时返回两个输出,就像在行中一样:
在两个变量val和中恢复这两个输出
maxVal
返回一对。您可以通过同时将任何元组的元素分配给适当数量的变量来“解构”任何元组。你知道吗
示例:
相关问题 更多 >
编程相关推荐