Почему мой метод Python продолжается после вызова оператора return? - PullRequest
0 голосов
/ 09 февраля 2020

При выполнении следующего метода он работает правильно, пока не достигнет точки, где он достигнет первого оператора return, где он возвращает путь. В этот момент он не выходит из метода, а переходит со второй на последнюю строку, где метод затем вызывается снова, вызывая бесконечную рекурсию. Разве метод не должен выходить автоматически после вызова return?

def main():
    if len(sys.argv) > 2:
        sys.exit("Usage: python degrees.py [directory]")
    directory = sys.argv[1] if len(sys.argv) == 2 else "small"

    # Load data from files into memory
    print("Loading data...")
    load_data(directory)
    print("Data loaded.")

    source = person_id_for_name(input("Name: "))
    if source is None:
        sys.exit("Person not found.")
    target = person_id_for_name(input("Name: "))
    if target is None:
        sys.exit("Person not found.")

    path = shortest_path(source, source, target, set(), list())

    if path is None:
        print("Not connected.")
    else:
        degrees = len(path)
        print(f"{degrees} degrees of separation.")
        path = [(None, source)] + path
        print(path)


def shortest_path(original, source, target, visitedpeople=set(), path=list()):
    """
    Returns the shortest list of person_id
    that connect the source to the target.

    If no possible path, returns None.
    """
    if source == target:
        return []
    while source != target:
        destinations = neighbors_for_person(source)
        visitedpeople.add(source)
        neighbors = list()
        for x in range(len(destinations)):
            neighbors.append(destinations[x])
        if neighbors.__contains__(target):
            for neighbor in destinations:
                if neighbor == target:
                    path.append(neighbor)
            return path
        else:
            if all(x in visitedpeople for x in neighbors):
                shortest_path(original, original, target, visitedpeople, path)
            else:
                for neighbor in destinations:
                    if neighbor not in visitedpeople:
                        path.append(neighbor)
                        visitedpeople.add(neighbor)
                        shortest_path(original, neighbor, target, visitedpeople, path)
    return []

...