Как я могу ссылаться на список, инициализированный в функции? (Python) - PullRequest
0 голосов
/ 23 апреля 2020

Ошибка, которую я получаю, - локальная переменная 'actions', на которую ссылаются перед присваиванием. У меня такое ощущение, что это потому, что я создаю список внутри функции, а затем пытаюсь ссылаться на него внутри. Это указанный c код, из которого я получил ошибку.

if node.state == target:
            actions: []
            cells: []

            while node.parent is not None:
                actions.append(node.action)
                cells.append(node.state)
                node = node.parent

Это больше контекста для источника кода, который я пишу.

def shortest_path(source, target):

    """
    Returns the shortest list of (movie_id, person_id) pairs
    that connect the source to the target.

    If no possible path, returns None.
    """
    # Create a frontier
    frontier = QueueFrontier()

    # Initialise explored set
    explored = set()
    # Create a start Node
    node = Node(state=source, parent=None, action=None)
    # Start with the source as a node (The initial state) and add it to the frontier
    frontier.add(node)
    # Start looping until we get a solution
    while True:
        # Check if Frontier is empty then no solution
        if frontier.empty():
            raise Exception("No path found")
        # Remove node from the frontier
        node = frontier.remove()
        # Check if node contains the goal state
        if node.state == target:
            actions: []
            cells: []

            while node.parent is not None:
                actions.append(node.action)
                cells.append(node.state)
                node = node.parent
            actions.reverse()
            cells.reverse()
            solution = (actions, cells)
            return solution

Я действительно ценю любую помощь в этом.

1 Ответ

0 голосов
/ 23 апреля 2020

используйте = для назначения

if node.state == target:
    actions = []
    cells = []

    while node.parent is not None:
        actions.append(node.action)
        cells.append(node.state)
        node = node.parent
...