![](/img/trans.png)
[英]Portion of code running only in the first iteration through a for loop in python
[英]Loop not running and get struck with the first iteration -Python Knapsack problem (No error)
自己是 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)+'>'
块 2
def buildMenu(names,values,calories):
menu=[]
for i in range(len(values)):
menu.append(Food(names[i],values[i],calories[i]))
return menu
块 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)
块 4
def testGreedy(items,constraint,keyFunction):
taken,val=greedy(items,constraint,keyFunction)
print('Total value of items taken',val)
for item in taken:
print(' ',item)
第 5 块
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)
下面的当前输出仅采用第一个元素。实际上,它应该针对名称中的整个输入项列表运行。
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>
请求您帮助调试并找出完整循环未按预期运行的原因。
当您构建菜单时,您对menu
return
处于循环中。 这会导致它只返回菜单中的一项,将其移回一个缩进。
def buildMenu(names,values,calories):
menu=[]
for i in range(len(values)):
menu.append(Food(names[i],values[i],calories[i]))
return menu
Total value of items taken 318.0
apple: <50,95>
wine: <89,123>
cola: <79,150>
beer: <90,154>
donut: <10,195>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.