循环未运行并被第一次迭代击中-Python背包问题无错误

问题描述

Python的新手,并在已经运行的代码上尝试我的技能。无法获得所需的输出作为输出列表,而只能获取一个输入和详细信息。

功能代码块。 第1块

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)+'>'

block-2

def buildMenu(names,values,calories):
    menu=[]
    for i in range(len(values)):
        menu.append(Food(names[i],values[i],calories[i]))
        return menu

block-3

def greedy(items,maxCost,keyFunction):
    itemscopy=sorted(items,key=keyFunction,reverse=True)
    result=[]
    totalValue,totalCost=0.0,0.0
    
    for i in range(len(itemscopy)):
        if(totalCost+itemscopy[i].getCost())<=maxCost:
            result.append(itemscopy[i])
            totalCost+=itemscopy[i].getCost()
            totalValue+=itemscopy[i].getValue()
    return (result,totalValue)

block-4

def testGreedy(items,constraint,keyFunction):
    taken,val=greedy(items,keyFunction)
    print('Total value of items taken',val)
    for item in taken:
        print('  ',item)

block-5

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

主要代码块和输入。

names=['wine','beer','pizza','burger','fries','cola','apple','donut','cake']
values=[89,90,95,100,79,50,10]
calories=[123,154,258,354,365,150,195]
foods=buildMenu(names,calories)
testGreedys(foods,750)

下面的当前输出仅占用第一个元素。实际上,它应在名称中的整个输入项目列表中运行。

Use greedy by value to allocate 750 calories
Total value of items taken 89.0
   wine: <89,123>

Use greedy by cost to allocate 750 calories
Total value of items taken 89.0
   wine: <89,123>

Use greedy by density to allocate 750 calories
Total value of items taken 89.0
   wine: <89,123>

请求您的调试帮助,找出为什么完整循环未按预期运行。

解决方法

构建菜单时,return的{​​{1}}处于循环中。这样一来,它只会返回菜单中的一项,将其移回一个缩进。

menu