Python中递归的全局变量
我在回溯方面遇到了一些困难Python中递归的全局变量,python,global-variables,backtracking,recursive-backtracking,Python,Global Variables,Backtracking,Recursive Backtracking,我在回溯方面遇到了一些困难 如何定义用于回溯问题的全局列表?我看到了一些答案,他们都建议在变量名前面使用'global'关键字,在函数中用作全局变量。然而,这给了我一个错误 有没有什么好的通用方法可以用来获得结果,而不是全局变量 下面的代码试图解决回溯问题,其中给出了一个数字列表,我们必须找到添加到目标的唯一数字对(不允许排列) For example, given candidate set [2, 3, 6, 7] and target 7, A solution set is: [
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
///////////////////////////////CODE/////////////////////////////
seen = []
res = []
def func(candidates, k, anc_choice): #k == target
#global res -- gives me an error -- global name 'res' is not defined
if sum(anc_choice) == k:
temp = set(anc_choice)
flag = 0
for s in seen:
if s == temp:
flag = 1
if flag == 0:
seen.append(temp)
print(anc_choice) #this gives me the correct answer
res.append(anc_choice) #this doesn't give me the correct answer?
print(res)
else:
for c in candidates:
if c <= k:
anc_choice.append(c) #choose and append
if sum(anc_choice) <= k:
func(candidates, k, anc_choice) #explore
anc_choice.pop() #unchoose
func(candidates, k, [])
例如,给定候选集[2,3,6,7]和目标7,
解决方案集是:
[
[7],
[2, 2, 3]
]
///////////////////////////////代码/////////////////////////////
SEED=[]
res=[]
def func(候选人、k、anc#U选择):#k==目标
#全局res--给我一个错误--未定义全局名称'res'
如果总和(anc_选择)=k:
温度=设置(anc_选择)
标志=0
对于SEED中的s:
如果s==温度:
标志=1
如果标志==0:
seen.append(临时)
打印(anc#U选项)#这给了我正确的答案
res.append(anc_choice)#这没有给我正确的答案吗?
打印(res)
其他:
对于c级候选人:
如果c要使用global关键字,您首先需要在实例化它之前将其声明为global
global res
res = []
虽然从你的代码看。由于res=[]
在函数之外,因此它已经全局可用。要使用全局关键字,首先需要在实例化它之前将其声明为全局
global res
res = []
虽然从你的代码看。因为res=[]
在函数之外,所以它已经在全局可用。有很多
如果需要更新上述范围内列表的函数,只需将列表作为参数传递即可。列表是可变的,因此它将在函数调用后更新
这里是一个简化的例子
res = []
def func(candidate, res):
res.append(candidate)
func(1, res)
res # [1]
这里有很多
如果需要更新上述范围内列表的函数,只需将列表作为参数传递即可。列表是可变的,因此它将在函数调用后更新
这里是一个简化的例子
res = []
def func(candidate, res):
res.append(candidate)
func(1, res)
res # [1]
foo=[]定义栏():全局foo。。。foo=[1]
是这样的吗?对不起,我是新手。我同意@johnashu。因为你已经有了函数外的res,所以它是全局的。你不需要把global关键字放在函数中,你只需要把它当作其他变量来使用,但是我不能在递归中使用和更改res。我该怎么做?foo=[]定义栏():全局foo。。。foo=[1]
是这样的吗?对不起,我是新手。我同意@johnashu。因为你已经有了函数外的res,所以它是全局的。你不需要把global关键字放在函数中,你只需要把它当作其他变量来使用,但是我不能在递归中使用和更改res。我该怎么做?