python - 即使在进行赋值时,在赋值之前也引用了局部变量
问题描述
我有一个背包问题的递归版本,并且在赋值错误之前引用了一个局部变量。但是,鉴于 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'])
解决方案
该if
块不保证运行,因此max_with_inclusion
不保证存在。当你打电话时,max
你会在分配前得到它的引用。if
在块之前或块中使用某个值初始化 var else
,例如max_with_inclusion = -1
对默认值有意义的任何值。
推荐阅读
- bash - shell如何删除具有几乎相同名称对的列表模式的第一个文件/文件夹
- google-sheets - 对 Google 表格中特定工作表的特定权限
- javascript - 从前端 Web 服务器调用 API 服务器
- python - 获取 botframework Python 中的活动对话框 ID - 具有多个对话框和 QnA Maker 的调度模型
- java - Gradle:使用两个不同的库但包名称相同的重复类错误
- javascript - 如何从javascript中的函数外访问函数中的变量
- javascript - 是否可以将 javascript 对象的 get 项定义为函数?
- java - onClick int 值更新到 Firebase 实时数据库
- react-native - React Native:成功登录后将电子邮件数组存储在 AsyncStorage 中
- node.js - 如何使用 Cloud Function 从 Cloud Storage for Firebase 获取对象?