簡體   English   中英

循環未運行並在第一次迭代中受到打擊 - 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM