【问题标题】:Is there a way to print the contents added to a knapsack for this 0/1 Greedy algorithm?有没有办法打印这个 0/1 贪婪算法添加到背包的内容?
【发布时间】:2020-12-03 05:13:29
【问题描述】:

我最近的实验室任务是尝试为 0/1 背包问题实现一个贪心算法,并打印出背包的内容以及背包的总价值。到目前为止,我能够让它毫无问题地输出背包的总价值,但是我在输出背包中的物品时遇到了问题。

#class definitions for the greedy approach
class Item: 
    def __init__(self,weight,value):
        self.weight = weight
        self.value = value
        self.price_kg = value / weight
    def __repr__(self):
        return f"Item(weight={self.weight}, value={self.value},v/w={self.price_kg})\n"

class Knapsack: 
    def __init__(self,max_weight,items):
        self.max_weight = max_weight
        self.items = items
        self.contents = list()

    def fillGreedy(self):
        self.items.sort(key=lambda x: x.price_kg, reverse=True)#sorts the items by weight/value
        for i in self.items:
            self.contents.append(i)#Tries putting the item in the bag
            if sum(i.weight for i in self.contents) > self.max_weight:
                self.contents.remove(i)#Removes the item it is too heavy for the bag
            elif sum(i.weight for i in self.contents) == self.max_weight:#finds an optimal configuration for the bag
                return sum(i.value for i in self.contents)
            
        return sum(i.value for i in self.contents)

#main method
max_weights = [10, 13, 15, 30, 30]
weights = [
    [4, 5, 7],
    [6, 5, 7, 3, 1],
    [2, 3, 5, 5, 3, 7],
    [10, 13, 17, 15],
    [5, 4, 7, 6, 3, 4, 2, 1, 7, 6]
]
values = [
    [2, 3, 4],
    [7, 3, 4, 4, 3],
    [3, 4, 10, 9, 6, 13],
    [21, 17, 30, 23],
    [3, 1, 3, 2, 1, 3, 2, 3, 1, 4]
]

for i in range(len(max_weights)):
    items = list()
    for j in range(len(weights[i])):
        items.append(Item(weights[i][j], values[i][j])) #adds the contents of the arrays to the Items list
 i
    ks = Knapsack(max_weights[i], items)
    v1 = ks.fillGreedy()
    print(f"Total value = {v1}")
    #print(items)

到目前为止,我尝试打印出 ks 和 v1 对象的内容,但这仅给出了对象的内存地址。在遍历 fillGreedy 方法后,我尝试打印出“项目”列表本身,但它打印出列表的所有内容,而不是背包本身的内容。我还尝试在 fillGreedy 方法中做一些事情来打印刚刚添加的项目,但它最终导致了冲突。我不确定从这里继续。有没有办法用这种方法打印出背包里的物品?

【问题讨论】:

  • 您发布的代码似乎超出了您的问题的合理范围。请阅读How to Ask 以及如何制作minimal reproducible example;提供 MRE 可帮助用户回答您的问题,并帮助未来的用户与您的问题相关。

标签: python python-3.x knapsack-problem


【解决方案1】:

欢迎来到本站。

您已经在 Knapsack 对象中拥有一个选定项目的集合,因此您可以遍历 ks.contents 并从那里打印出内容或所需的任何内容...

for item in ks.contents:
    print(item)

【讨论】:

  • 当然。如果问题得到回答,您应该通过点击上面的复选标记将其关闭来“接受”答案。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
相关资源
最近更新 更多