【问题标题】:Knapsack recursive function背包递归函数
【发布时间】:2016-11-20 03:05:08
【问题描述】:

我有一个名为 self.items 的列表,其中的元素是:

items = [dict(id=0, w=4, v=12),
         dict(id=1, w=6, v=10),
         dict(id=2, w=5, v=8),
         dict(id=3, w=7, v=11),
         dict(id=4, w=3, v=14),
         dict(id=5, w=1, v=7),
         dict(id=6, w=6, v=9)]

有了这个我必须做一个列表列表,其中每个元素都有所有可能的组合,包括空的情况,所以最后我的列表或多或少有这样的外观:

[[],[{id:0,w:4,v:12}],....,[{id:0,w:4,v:12}, {id:1,w:6,v:10}]....]

现在我必须找到一个递归函数来搜索哪些元素组合具有允许的最大权重和最大值。

 def recursive(self, n, max_weight):
""" Recursive Knapsack
:param n: Number of elements
:param max_weight: Maximum weight allowed
:return: max_value
"""
self.iterations += 1 
result = 0

if max_weight > self.max_weight: #they gave me self.max_weight as a variable of  __init__ method which shows me what is the maximum weight permitted
    self.recursive(self, self.items+self.iterations, max_weight)
    if max_weight < self.max_weight:
        self.recursive(self, self.items+self.iterations, max_weight)
    else:
            result = self.items['v']+result

return result

我认为我的错误在这一行:

result = self.items['v']+result

但我找不到它。

【问题讨论】:

  • 您遇到的错误是什么?你期待什么结果?你得到了什么?
  • 我没有收到任何错误,但它不起作用。我期望的结果是 max_value=44 并且我得到 max_value=0 这是所选项目的总和为 44 Selected items: [{'id': 0, 'w': 4, 'v': 12}, {'id': 1, 'w': 6, 'v': 10}, {'id': 2, 'w': 5, 'v': 8}, {'id': 4, 'w': 3, 'v': 14}] 这是应用我的代码的结果:Method: recursive Iterations:1 Max value:0 expected max_value:44

标签: python recursion


【解决方案1】:

我刚刚找到了解决这个递归问题的方法: (我来自西班牙,所以变量“cantidad”也表示“数量”)

 def recursive(self, n, max_weight):
    """ Recursive Knapsack
    :param n: Number of elements
    :param max_weight: Maximum weight allowed
    :return: max_valu
    """
    self.iterations += 1
    result = 0
    cantidad = 0
    quantity = 0

    if max_weight == 0 or n == 1:
        if  max_weight >= self.items[n-1]['w'] :
            cantidad= self.items[n-1]['v']

        return max(cantidad,quantity)
    else:
        if  max_weight >= self.items[n-1]['w']:
            cantidad = self.items[n-1]['v']+self.recursive(n-1,max_weight-self.items[n-1]['w'])

        quantity = self.recursive(n-1,max_weight)
        result = max(cantidad, quantity)
        return result

我将此代码放入我正在学习的大学按比例分配的程序中,它返回给我正确的结果:

Method: recursive
Iterations:107
Max value:44 expected max_value:44

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2015-03-01
    • 2012-04-06
    相关资源
    最近更新 更多