0

To maximize the value of the knapsack

The output should like this
>>>Bags=[mkBag('cooper',30,120),mkBag('silver',20,100),mkBag('gold',10,60)]
>>>knapsack(Bags,50)
[('gold',1.0),('silver',1.0),mkBag('copper',0.666666666)]

class Bag():
    __slots__ = ('name', 'weight','value', 'ratio')

def mkBag(name,weight,value):
    bag=Bag()
    bag.name = name
    bag.weight = weight
    bag.value = value
    bag.ratio=value//weight
    return bag

def printbag(bags):
    print("Name:", bag.name, "Weight:",bag,weight,"Value:", bag.value)

def knapsack(bags,maxweight):
    bags=sorted(bags, key=lambda mkBag: mkBag.ratio)
    bags.reverse()
    get_list=[]
    for bag in bags:
        print(bag.name, bag.weight, bag.value)
    
    while maxweight>0 and len(bags)>0:
        for bag in bags:
            if bag.weight[2] < maxweight:
                maxweight=maxweight-bag.weight[0]
                
            #I am stuck here. Don't know what to do now
                

        


    
  
bags=[mkBag('Copper', 30, 130),mkBag('silver', 20, 100),
        mkBag('gold', 10, 60 ),]


maxweight=50
knapsack(bags,maxweight)
2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by pyTony
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.