繁体   English   中英

用于Python中递归的全局变量

[英]Global variable for recursion in Python

我在回溯中面临一些困难。

  1. 如何定义用于回溯问题的全局列表? 我看到了两个答案,他们都建议在函数名称内的变量名前面使用'global'关键字,以用作全局名称。 但是,这给了我一个错误。

  2. 有什么好的通用方法可以代替全局变量来获取结果?

下面的代码试图解决回溯问题,其中给出了一个数字列表,并且我们必须找到添加到目标的唯一数字对(不允许排列)。

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, [])

有人可以给我答案/建议吗?

要使用global关键字,您首先需要在实例化之前将其声明为全局。

global res
res = []

虽然从看你的代码。 由于res = []在函数外部,因此它已经全局可用。

有许多原因导致您不应该使用全局变量

如果您想要一个在上述范围内更新列表的函数,只需将列表作为参数传递即可。 列表是可变的,因此它将在函数调用后进行更新。

这是一个简化的示例。

res = []

def func(candidate, res):
    res.append(candidate)

func(1, res)

res # [1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM