Python中

时间:2018-03-16 03:05:27

标签: python global-variables backtracking recursive-backtracking

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

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

  2. 是否有可用于获取结果的通用方法,而不是全局变量?

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

    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 个答案:

答案 0 :(得分:1)

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

Array
(
[0] => stdClass Object
(
[category] => AUTHENTICATION_ERROR
[code] => UNAUTHORIZED
[detail] => This request could not be authorized.
)

)
Order status changed from Pending payment to Failed.

虽然从查看你的代码。由于global res res = [] 不在函数范围内,因此它已在全球范围内可用。

答案 1 :(得分:0)

有很多reasons why you should not use global variables

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

这是一个简化的例子。

res = []

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

func(1, res)

res # [1]