首页 > 解决方案 > 即使在进行赋值时,在赋值之前也引用了局部变量

问题描述

我有一个背包问题的递归版本,并且在赋值错误之前引用了一个局部变量。但是,鉴于 of 的声明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'])

标签: python

解决方案


if块不保证运行,因此max_with_inclusion不保证存在。当你打电话时,max你会在分配前得到它的引用。if在块之前或块中使用某个值初始化 var else,例如max_with_inclusion = -1对默认值有意义的任何值。


推荐阅读