Fedora-The-Explorer
Fedora-The-Explorer

Reputation: 13

Stopping a recursive function in Python

The program should od as follows: Find out if two people are connected (directly or indirectly) and list out the path over which the two people are connected, using recursion. The problem occurs in the line return True, as the recursion doesn't break and just continues as if the if statement was not true.

def trace(info, first, second):
    for a, b in info:
        if a == first:
            print(a, b)
            if b == second:
                return True
            else:
                trace(info, b, second)
    return False
    


info = [('zayn', 'anna'), ('jake', 'maria'), ('pete', 'anna'), ('travis', 'hannah'), ('maria', 'sara'), ('anna', 'mark'), ('sara', 'zayn'), ('sara', 'pete'), ('sara', 'mark')]

trace(info, 'jake', 'mark')

Upvotes: 1

Views: 58

Answers (1)

Netwave
Netwave

Reputation: 42746

You are missing the return statement from the recursive call:

def trace(info, first, second):
    for a, b in info:
        if a == first:
            print(a, b)
            if b == second:
                return True
            else:
                return trace(info, b, second)
    return False

Playground

Upvotes: 2

Related Questions