【发布时间】: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