我有一个背包问题的递归版本,并在分配错误之前引用了一个局部变量。但是考虑到max_with_inclusion = recursive ...
本身就是赋值,这还行吗?通常,我习惯于在python中分配变量,就像不需要类型信息一样。有人可以在这里解释问题吗?
def recursive_max_helper(knapsack_max_weight,items,index,max_so_far):
if index == len(items):
return max_so_far
# Uncomment removes error max_with_inclusion = max_with_exclusion = 0
if knapsack_max_weight - items[index].weight >= 0:
max_with_inclusion = recursive_max_helper(knapsack_max_weight - items[index].weight,items,index+1,max_so_far+items[index].value)
max_with_exclusion = recursive_max_helper(knapsack_max_weight,items,index+1,max_so_far)
return max(max_with_exclusion,max_with_inclusion)
tests = [
{
'correct_output': 14,
'input':
{
'knapsack_max_weight': 15,
'items': [Item(10, 7), Item(9, 8), Item(5, 6)]}},
{
'correct_output': 13,
'input':
{
'knapsack_max_weight': 25,
'items': [Item(10, 2), Item(29, 10), Item(5, 7), Item(5, 3), Item(5, 1), Item(24, 12)]}}]
for test in tests:
assert test['correct_output'] == recursive_max_value(**test['input'])
答案 0 :(得分:3)
max_with_inclusion
仅在您的if
条件评估为True
时设置。所以不,在knapsack_max_weight < items[index].weight
时不会设置变量。
两个简单的解决方案:
else
子句以确保设置了max_with_inclusion
。答案 1 :(得分:3)
不能保证if
块可以运行,因此不能保证max_with_inclusion
存在。调用max
时,会在分配前引用它。用if
块之前或else
块中的某个值初始化var,例如max_with_inclusion = -1
或其他有意义的默认值。