您好我正在编写和测试一个递归动态编程背包(0-1)(以下代码是主文件和函数)我不断收到错误(在代码后发布)...我真的对于错误是什么感到困惑,所以任何帮助都会非常感激!
import Knapsack_Test
size = 10
W = 2**size
knapsack = Knapsack_Test.Knapsack_Test()
for i in range(1, 10):
knapsack.recursive_knapsack_test(size, W)
size = size + 100*i
W = 2**size
def recursive_dynamic_knap(self, v, w, i, W):
n = len(v) - 1
if i == n:
if W < w[n]:
return 0
else:
return v
elif W < w[i]:
return self.recursive_dynamic_knap(v, w, i+1, W)
return max(self.recursive_dynamic_knap(v, w, i+1,W), self.recursive_dynamic_knap(v, w, i+1, W-w[i]) + v[i])
Traceback (most recent call last):
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\Knapsack_Main.py", line 9, in <module>
knapsack.recursive_knapsack_test(size, W)
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\Knapsack_Test.py", line 19, in recursive_knapsack_test
self.knapsack.recursive_dynamic_knap(v, w, j, W)
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 22, in recursive_dynamic_knap
return max(self.recursive_dynamic_knap(v, w, i+1,W), self.recursive_dynamic_knap(v, w, i+1, W-w[i]) + v[i])
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 22, in recursive_dynamic_knap
return max(self.recursive_dynamic_knap(v, w, i+1,W), self.recursive_dynamic_knap(v, w, i+1, W-w[i]) + v[i])
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 22, in recursive_dynamic_knap
return max(self.recursive_dynamic_knap(v, w, i+1,W), self.recursive_dynamic_knap(v, w, i+1, W-w[i]) + v[i])
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 22, in recursive_dynamic_knap
return max(self.recursive_dynamic_knap(v, w, i+1,W), self.recursive_dynamic_knap(v, w, i+1, W-w[i]) + v[i])
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 22, in recursive_dynamic_knap
return max(self.recursive_dynamic_knap(v, w, i+1,W), self.recursive_dynamic_knap(v, w, i+1, W-w[i]) + v[i])
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 22, in recursive_dynamic_knap
return max(self.recursive_dynamic_knap(v, w, i+1,W), self.recursive_dynamic_knap(v, w, i+1, W-w[i]) + v[i])
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 22, in recursive_dynamic_knap
return max(self.recursive_dynamic_knap(v, w, i+1,W), self.recursive_dynamic_knap(v, w, i+1, W-w[i]) + v[i])
TypeError: unorderable types: int() > list()
答案 0 :(得分:2)
我认为问题在于return max(self.recursive_dynamic_knap(v, w, i+1,W), self.recursive_dynamic_knap(v, w, i+1, W-w[i]) + v[i])
对recursive_dynamic_knap
的一次调用正在返回v
,这是一个列表,并且作为{{1}的参数毫无意义因为它是“无法解决的”(不能明智地被判断为大于或小于max()
)