简体   繁体   中英

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. 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:

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. Can you help me please ?

One key problem is that:

if solutie:

is testing the truthiness of the function , which will always be 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 ? 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 . Although you assign k += 1 in back , the other functions (eg valid ) are still using k == 0 from the outer scope. 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 . 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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