1

I've done a maze pathfinding recursive function as homework but I'm encountering a problem. I know I've done everything correctly (through debugging), the path is being found etc. But when all the recursive functions start returning True, the original/first one isn't! I can't find a way to make it return true ( the recursive call are in a "if, true" format).

I hope you guys can help me, and sorry for bad english since it isn't my mother language.

*Here goes the code:

def pathExists(labyrinth, currCoord, destination, previousRule, visited):
    if currCoord == destination:
        return True
    if currCoord not in labyrinth:
        print "False"
        return False

    rule = labyrinth[currCoord]
    if rule == Any:
        previousRule = rule
        print currCoord
        if (pathExists(labyrinth, (currCoord[0], currCoord[1] - 1), destination, rule, visited) or
            pathExists(labyrinth, (currCoord[0] + 1, currCoord[1]), destination, rule, visited) or
            pathExists(labyrinth, (currCoord[0] - 1, currCoord[1]), destination, rule, visited) or
            pathExists(labyrinth, (currCoord[0], currCoord[1] + 1), destination, rule, visited)):
            print "True"
            return True
        else:
            print"outro"

    elif rule == Bridge:
        print currCoord
        currCoord = nextCoord(currCoord, previousRule)
        if pathExists(labyrinth, currCoord, destination, rule, visited):
            print "True"
            return True

    else:
        print currCoord
        if currCoord in visited:
                print "False"
                return False
        visited.append(currCoord)
        previousRule = rule
        currCoord = nextCoord(currCoord, rule)
        if pathExists(labyrinth, currCoord, destination, rule, visited):
            print "True"
            return True
asermax
  • 3,053
  • 2
  • 23
  • 28

1 Answers1

0

Without all code I my be wrong, but I think that you need a global/class var to store return value. The logic: first call does not return anything(or return None) since is calling other function.
To be clear:

a = [1,2,[4,6],3,4]
ret = None
def f(x):
    global ret
    if isinstance(x, list):
        f(x[0])
    else:
        ret = x
        return x

var = f(a)
print(var, ret)

If you test, you will see var = None, but ret is 1 (instead of global I suggest you to incapsulate code in a class and use something like self.ret).

P.S.: As Joel Cornett said, using english / abstract var names make all code a lot more readable!

cox
  • 731
  • 5
  • 12