即使在分配时也要在分配前引用局部变量

时间:2019-07-02 19:21:14

标签: python

我有一个背包问题的递归版本,并在分配错误之前引用了一个局部变量。但是考虑到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'])

2 个答案:

答案 0 :(得分:3)

max_with_inclusion仅在您的if条件评估为True时设置。所以不,在knapsack_max_weight < items[index].weight时不会设置变量。

两个简单的解决方案:

  1. 根据您的评论建议,在所有情况下都进行预分配。
  2. 添加一个else子句以确保设置了max_with_inclusion

答案 1 :(得分:3)

不能保证if块可以运行,因此不能保证max_with_inclusion存在。调用max时,会在分配前引用它。用if块之前或else块中的某个值初始化var,例如max_with_inclusion = -1或其他有意义的默认值。