简体   繁体   English

Python回溯

[英]Backtracking in Python

I have just started learning Python and tried to write down the backtracking algorithm, but it seems that I am doing something wrong. 我刚开始学习Python并尝试写下回溯算法,但是看来我做错了。 Since I am new to this language, I have been trying to look it up on the internet, but did not understand very much of it.Here is my code: 由于我是这种语言的新手,所以我一直试图在Internet上查找它,但对它的了解不是很多,这是我的代码:

n = 3
x = [0] * 3
k = 0
def init ():
    x[k] = 0
def succesor():
    if x[k] < n:
        x[k]+=1
        return 1
    return 0
def valid ():
    i = 1
    for i in range (0,k-1):
        if x[i] == x[k]:
            return 0
    return 1
def solutie ():
    return k == n
def afis():
    print(x)
def back ():
    k = 1
    avemsuccesor = 1
    init()
    while k > 0:
        while avemsuccesor and not valid():
            avemsuccesor = succesor()
        if avemsuccesor:
            if solutie:
                afis()
            else:
                k+=1
                init()
        else:
            k-=1
def main ():
    back()
main ()

When I run it, I only get a vector full of 0's. 运行它时,我只会得到一个全为0的向量。 Can you help me please ? 你能帮我吗 ?

One key problem is that: 一个关键问题是:

if solutie:

is testing the truthiness of the function , which will always be True : 正在测试函数的真实性,该真实性将始终为True

>>> bool(solutie)
True

rather than the truthiness of the value it returns; 而不是它返回的价值的真实性; you should have: 你应该有:

if solutie():
        # ^ note parentheses

Also, none of your functions have arguments, so you rely entirely on variable scope for access. 另外,您的函数都没有参数,因此您完全依赖变量作用域进行访问。 This is unwise, and makes the code very difficult to debug - you can't test any function in isolation. 这是不明智的,并且使代码非常难以调试-您无法单独测试任何功能。 As a trivial example, compare: 举个简单的例子,比较一下:

def solutie():
    return k == n

with

def solutie(k, n):
    return k == n

With the former, testing is very difficult - what are k and n ? 对于前者,测试非常困难kn什么? Where do they come from? 他们来自哪里? With the latter, it's a simple matter of 对于后者,这很简单

assert solutie(1, 1)
assert not solutie(1, 2)

The main problem you have stems from this: because k is immutable, you always use the same value in every function other than back . 您遇到的主要问题k是不可变的,因此back之外,每个函数中始终使用相同的值 Although you assign k += 1 in back , the other functions (eg valid ) are still using k == 0 from the outer scope. 尽管您在back分配了k += 1 ,但其他函数(例如valid )仍在外部范围中使用k == 0 If you change every function to use explicit arguments and return values, eg: 如果更改每个函数以使用显式参数并返回值,例如:

 def successor(x, k, n):
     ...
     return True # use booleans rather than 0 or 1

 ...
     avemsuccesor = succesor(x, k, n) 

You will quickly find that k goes out of range, causing an IndexError . 您会很快发现k超出范围,从而导致IndexError I won't rewrite everything here - I will leave refactoring your code to pass values around explicitly and solving the errors that then crop up as an exercise for you. 我不会在这里重写所有内容-我将保留重构代码以显式传递值的方式,并解决错误,然后为您做练习。

The issue is that k is defined twice, once as 0 and once as 1. Inside valid, it chooses the global k = 0 but regardless, even k-1 is zero initially so valid() will return 1 on the first iteration. 问题在于,k被定义了两次,一次是0,一次是1。在有效内部,它选择全局k = 0,但是不管k-1最初是零,所以valid()在第一次迭代中将返回1。 I don't understand the intention of this program but that is the reason it never gets to run successor() which actually modifies the vector's elements from zeros. 我不理解该程序的意图,但这就是它永远无法运行后继者()的原因,后者实际上是将向量的元素从零修改为零。

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

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