Search code examples
pythonfunctionreturnterminatesuffix

Why is my function not terminating after return?


I'm creating a suffix tree using the string "BANANA$". When calling my findPath function from main as "print(findPath(root, "BANANA$", 5))", so checking if "A$" is a path from the root, I get the following output:

SEQUENCE: A$
  CUR CHILD: $
    NON-MATCH: $ 0
  CUR CHILD: A
    CHILD MATCHED: A
    NEW SEQ: $

SEQUENCE: $
  CUR CHILD: $
REACHED THE END!
  CUR CHILD: BANANA$
  CUR CHILD: NA
False

It prints out the line "REACHED THE END!", so clearly the function has touched that part of the code, bu why isn't my function terminating after the line "return True"?

def findPath(curNode, sequence, i):

    sequence = sequence[i:]
    print("\nSEQUENCE: " + sequence)

    for child in curNode.children:
        print("  CUR CHILD:", child.val)
        # print(len(child.val), child.val)

        # NO WAY IT CAN BE A MATCH, SO SKIP
        if (len(child.val) > len(sequence)):
            pass

        # POSSIBILITY TO MATCH
        else:
            curInd = 0
            count = 0

            # CHECK IF child.val MATCHES THE BEGINNING OF sequence
            while (curInd < len(child.val)):
                if (child.val[curInd] != sequence[curInd]):
                    print("    NON-MATCH:", child.val[curInd], curInd)
                    count += 1

                curInd += 1

            # child.val MATCHES THE BEGINNING OF sequence
            if (count == 0):
                # AN EXACT MATCH, SO REACHED THE END
                if (child.val == sequence):
                    print("REACHED THE END!")
                    return True

                else:
                    print("    CHILD MATCHED:", child.val)
                    newInd = len(child.val)
                    sequence = sequence[newInd:]
                    print("    NEW SEQ:", sequence)
                    findPath(child, sequence, 0)
    return False

Solution

  • After it returns from the recursive call, the parent function continues its for loop. If you want it to stop when the child has reached the end, you need to check the return value of the recursion.

                    else:
                        print("    CHILD MATCHED:", child.val)
                        newInd = len(child.val)
                        sequence = sequence[newInd:]
                        print("    NEW SEQ:", sequence)
                        if findPath(child, sequence, 0):
                            return True
    

    This will propagate the True value back up through the recursion stack.