Ejemplo n.º 1
0
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.
    """

    # TODO
    # Keep track of number of states explored
    num_explored = 0

    # Initialize frontier to just the starting position
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    explored = set()
    # Keep looping until solution found
    while True:

        # If nothing left in frontier, then no path
        if frontier.empty():
            raise Exception("no solution")

        # Choose a node from the frontier
        node = frontier.remove()
        num_explored += 1

        # If node is the goal, then we have a solution
        if node.state == target:
            answer = []
            while node.parent is not None:
                #action = movieid, state = personid
                answer.append((node.action, node.state))
                node = node.parent
            answer.reverse()
            return answer

        #Mark node as explored
        if node.state not in explored:
            explored.add(node.state)

        for action, state in neighbors_for_person(node.state):
            if not frontier.contains_state(state) and state not in explored:
                child = Node(state=state, parent=node, action=action)
                #if you detect a goal node, no need to add it to the frontier, you can simply return the solution immediately.
                if child.state == target:
                    answer = []
                    while child.parent is not None:
                        #action = movieid, state = personid
                        answer.append((child.action, child.state))
                        child = child.parent
                    answer.reverse()
                    return answer

                frontier.add(child)
                explored.add(child.state)
Ejemplo n.º 2
0
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.
    """
    # keep track of number of states explored
    num_explored = 0

    # state is person id
    # action is movie id

    # initialize frontier to starting position
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # initialize empty explored set
    explored = set()

    # keep looping until solution found
    while True:

        # if nothing in the frontier at start of loop, no path
        if frontier.empty():
            return (None)

        # choose a node from the frontier
        node = frontier.remove()
        num_explored += 1

        # if node is the goal, we have a solution
        # this should be the shortest path since we're using BFS
        if node.state == target:
            actions = []
            states = []
            while node.parent is not None:
                actions.append(node.action)
                states.append(node.state)
                node = node.parent
            actions.reverse()
            states.reverse()
            solution = []
            for i in range(len(actions)):
                solution.append((actions[i], states[i]))
            return (solution)

        explored.add(node.state)

        for action, state in neighbors_for_person(node.state):
            if not frontier.contains_state(state) and state not in explored:
                child = Node(state=state, parent=node, action=action)
                frontier.add(child)

    # TODO
    raise NotImplementedError
Ejemplo n.º 3
0
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.
    """

    num_explored = 0

    start = Node(state=start, parent=None, action=action)
    frontier = QueueFrontier()
    frontier.add(start)

    explored = set()

    # Loop until solution is found
    while True:
        if frontier.empty():
            return None

        node = frontier.remove()
        explored.add(node.state)

        solution = []

        for movie_id, person_id in neighbors_for_person(node.state):
            if not frontier.contains_state(person_id) and person_id not in explored:
                child = Node(person_id, node, movie_id)
                if child.state == target:
                    solution.append((movie_id, person_id))
                    while node.parent is not None:
                        solution.append((node.action, node.state))
                        nod = node.parent
                    solution.reverse()
                    return solution
                frontier.add(child)

        if node.state == goal:
            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

        explored.add(node.state)

        for action, state in neighbors(node.state):
            if not (frontier.contains_state(state) and state not in explored):
                child = Node(state=state, parent=node, action=action)
                frontier.add(child)
Ejemplo n.º 4
0
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.
    """

    # Initialize front to the start position
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # Initialize an empty set
    explored = set()

    #loop
    while True:

        # If nothing left in frontier, then no path
        if frontier.empty():
            return None

        # Choose a node from the frontier
        node = frontier.remove()
        num_explored += 1

        # If node is the goal, then we have a solution
        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

        # Mark node as explored
        explored.add(node.state)

        # Add neighbors to frontier
        for action, state in neighbors_for_person(node.state):
            if state not in explored and not frontier.contains_state(action):
                child = Node(state=state, parent=node, action=action)
                if child.state == target:
                    action_path = []
                    node = child
                    while node.parent is not None:
                        action_path.append((node.action, node.state))
                        node = node.parent

                    action_path.reverse()
                    return action_path
                frontier.add(child)
Ejemplo n.º 5
0
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.
    """

    # Initialize frontier to just the starting position
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)
    print('Target is ' + target)
    print(start.parent)

    # Keep looping until solution found
    while True:

        # If nothing left in frontier, then no path
        if frontier.empty():
            raise Exception("no solution")

        # Initialize an empty explored set
        explored = set()

        # Choose a node from the frontier
        node = frontier.remove()

        # If node is the goal, then we have a solution
        if node.state == target:
            print('there')
            solution = []
            link = set()
            while node.parent is not None:
                solution.append(((node.action), (node.state)))
                print(solution)
                node = node.parent
            print('no parent')
            solution.reverse()
            print(solution)
            return solution

        # Mark node as explored
        explored.add(node.state)
        print(neighbors_for_person(node.state))
        for person in neighbors_for_person(node.state):
            if not frontier.contains_state(
                    person[1]) and person[1] not in explored:
                print('Here')
                child = Node(state=person[1], parent=node, action=person[0])
                print(child.parent)
                frontier.add(child)
                if person[1] == target:
                    break

    # TODO
    raise NotImplementedError
Ejemplo n.º 6
0
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.
    """
    """ initialize frontier to start """
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # empty explored set
    explored = set()

    # Keep looping until solution found
    while True:

        # If nothing left in frontier, then no path
        if frontier.empty():
            return None

    # Choose a node from the frontier
        node = frontier.remove()

        # If node is the goal, then we have a solution
        if node.state == target:
            solution = []
            while node.parent is not None:
                x = node.action
                y = node.state
                solution.append((x, y))
                node = node.parent
            solution.reverse()
            return solution
    # if not add it to explored
        explored.add(node.state)

        # check neighbours of the node
        for mov, pop in neighbors_for_person(node.state):

            #check if node is solution before putting it in a frontier
            if pop == target:
                node = Node(state=pop, parent=node, action=mov)
                solution = []
                while node.parent is not None:
                    x = node.action
                    y = node.state
                    solution.append((x, y))
                    node = node.parent
                solution.reverse()
                return solution

            # else add node to the frontier
            elif not frontier.contains_state(pop) and pop not in explored:
                child = Node(state=pop, parent=node, action=mov)
                frontier.add(child)
Ejemplo n.º 7
0
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.
    """
    # TODO
    start = Node(state=source, parent=None, action=None)  # VA
    frontier = QueueFrontier()  # VA
    frontier.add(start)  # VA

    explored = set()  # VA -> MIRAR SI ES LOCAL A LA FUNCION

    while True:

        # If nothing left in frontier, then no path
        if frontier.empty():  # VA
            raise Exception("no solution")

        # Choose a node from the frontier
        node = frontier.remove()  # VA

        # If node is the goal, then we have a solution
        """
            if node.state == target:  # VA-> TARGET (VA TODO LO DEL IF)
                actions = []
                cells = []
                while node.parent is not None:
                    actions.append(node.action)
                    cells.append(node.state)
                    node = node.parent
                actions.reverse()
                cells.reverse()
                self.solution = (actions, cells)
                return
            """

        # Mark node as explored

        # Add neighbors to frontier
        # VA -> CON LA FUNCIÓN QUE TENEMOS
        for movie_id, person_id in neighbors_for_person(node.state):
            if not frontier.contains_state(
                    person_id) and person_id not in explored:
                if person_id == target:
                    path = []
                    path.append((movie_id, person_id))
                    while node.parent is not None:
                        path.append((node.action, node.state))
                        node = node.parent
                    path.reverse()
                    return path
                else:
                    child = Node(state=person_id, parent=node, action=movie_id)
                    frontier.add(child)
            explored.add(person_id)  # VA
Ejemplo n.º 8
0
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.
    """
    Frontier = QueueFrontier()

    exploredNodes = set()
    # exploredStartNodes = set()

    start = selectStart(source, target, exploredNodes, Frontier)
    if start == None:
        raise Exception("No solution")

    # exploredStartNodes.add(start.state)
    exploredNodes.add(start.state)

    while True:

        if Frontier.empty():
            newStart = selectStart(source, target, exploredNodes, Frontier)
            if newStart == None:
                raise Exception("No Solution")
            else:
                Frontier.add(newStart)
                # exploredStartNodes.add(newStart.state)
                exploredNodes.add(newStart.state)
        else:

            node = Frontier.remove()

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

                ##Add the current node and its parents
                cells.append(node.state)
                while (node.parent is not None):
                    cells.append(node.parent.state)
                    node = node.parent
                cells.reverse()
                return cells

            neighborsOfNodes = neighbors_for_person(node.state[1])

            for neighbor in neighborsOfNodes:
                if targetInNeighbors(neighborsOfNodes, target):
                    if neighbor[1] == target:
                        child = Node(state=neighbor, parent=node, action=None)
                        Frontier.add(child)
                        exploredNodes.add(child.state)
                elif neighbor not in exploredNodes and not Frontier.contains_state(
                        neighbor):
                    child = Node(state=neighbor, parent=node, action=None)
                    Frontier.add(child)
                    exploredNodes.add(child.state)
Ejemplo n.º 9
0
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.
    """

    #Initialize frontier to starting position
    source = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(source)

    #Explored Set
    explored = set()
    # TODO
    #Solution Loop
    while True:

        if frontier.empty():
            break

        node = frontier.remove()

        if node.state == target:
            solution = []
            while node.parent is not None:
                segment = (node.action, node.state)
                solution.append(segment)
                node = node.parent
            solution.reverse()

            return solution

        explored.add(node.state)

        #add neighbors to frontier
        neighbors = neighbors_for_person(node.state)
        for costars in neighbors:
            if costars[1] == target:
                solution = []
                finalnodes = Node(state=target, parent=node, action=costars[0])
                while finalnodes.parent is not None:
                    segment = (finalnodes.action, finalnodes.state)
                    solution.append(segment)
                    finalnodes = finalnodes.parent
                solution.reverse()

                return solution

            if not frontier.contains_state(
                    costars[1]) and costars[1] not in explored:
                child = Node(state=costars[1], parent=node, action=costars[0])
                frontier.add(child)

    return None
    raise NotImplementedError
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.
    node.state will be an actor, and node.action will be the movie taken to get from one actor to the next.
    """

    # Initialize frontier to just the starting actor
    start = Node(state=(source), parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # Initialize an empty explored set
    explored = set()

    while True:

        # If nothing left in frontier, then no path
        if frontier.empty():
            raise Exception("No solution.")

        # Choose a node from the frontier
        node = frontier.remove()
        #print (f'Node popped: {node.state}')
        # check for target in film node.
        explored.add(node.state)

        # if node.state == target:
        #     solution = []
        #     while node.parent is not None:
        #         solution.append((node.action, node.state))
        #         node = node.parent
        #     solution.reverse()
        #     return solution
        neighbors = []
        for movie, actor in neighbors_for_person(node.state):
            if actor not in neighbors:
                neighbors.append(actor)

            if target in neighbors:
                solution = []
                solution.append((movie, target))
                while node.parent is not None:
                    solution.append((node.action, node.state))
                    node = node.parent
                solution.reverse()
                return solution

        nodecounter = 0
        for movie, actor in neighbors_for_person(node.state):
            if not frontier.contains_state(actor) and actor not in explored:
                child = Node(state=actor, parent=node, action=movie)
                frontier.add(child)
                nodecounter += 1
Ejemplo n.º 11
0
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.
    """

    frontier = QueueFrontier()
    explored = set()  # person IDs already explored

    initialnode = Node(source, None, None)
    frontier.add(initialnode)

    while not frontier.empty():

        # Remove a node from the frontier (QUEUE)
        currentnode = frontier.remove()

        # Skip Node if already explored (personID)
        if currentnode.state in explored:
            continue

        # Obtain the list of (movie, personid) that the source is in
        setofneighbors = neighbors_for_person(currentnode.state)

        for movieid, personid in setofneighbors:

            # Create a Node for neighbor
            checknode = Node(personid, currentnode, movieid)

            # Check if person is the target
            if target == checknode.state:
                reversedSolution = []
                tempnode = checknode

                # Make sure we are not at the Initial Node where Parent = None
                while tempnode.parent != None:
                    # print(f"Person {tempnode.state}, Movie{tempnode.action}")
                    # Add the current node to the Solution List
                    reversedSolution.append((tempnode.action, tempnode.state))

                    # Obtain the parent of the current node to backtrack to the beginning
                    tempnode = tempnode.parent

                # Reverse the Solution to display path from Start to End
                return reversedSolution[::-1]

            # Add the node to the frontier to be analyzed later
            else:
                frontier.add(checknode)

        # Add it after its been explored
        explored.add(currentnode.state)

    return None
Ejemplo n.º 12
0
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.
    """

    # Keep track of number of states explored
    num_explored = 0

    # Initialize frontier to just the starting position
    ageGap = find_age_gap(target, source)
    start = Node(state=source,
                 parent=None,
                 action=None,
                 heuristic=ageGap,
                 cost=num_explored)
    frontier = AFrontier()
    frontier.add(start)

    # Initialize an empty explored set
    explored = set()

    while True:

        # Empty Frontier returns no solution
        if frontier.empty():
            raise Exception("No solution")

        # Select a Node from the frontier
        node = frontier.remove()
        num_explored += 1

        # check if node matches target and return solution
        if node.state == target:
            solution = solution_path(node)
            return solution, num_explored

        # Mark node as explored if it is not the goal
        explored.add(node.state)

        # Add neighbors to frontier
        for action, state in neighbors_for_person(node.state):
            # check if neighbor is the goal
            if state == target:
                solution = solution_path(node)
            # Don't add node to frontier if we have already explored it or it is already in the frontier
            if not frontier.contains_state(state) and state not in explored:
                ageGap = find_age_gap(target, state)
                child = Node(state=state,
                             parent=node,
                             action=action,
                             heuristic=ageGap,
                             cost=num_explored)
                frontier.add(child)
Ejemplo n.º 13
0
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.
    """

    # TODO
    #actions = movies
    #states = people_id

    start = Node(state=source, parent=None, action=None)

    #BFS search
    frontier = QueueFrontier()
    frontier.add(start)

    # Initialize an empty explored set
    explored = set()

    # Keep looping until solution found
    while True:

        # If nothing left in frontier, then return none
        if frontier.empty():
            return None

        # Choose a node from the frontier
        node = frontier.remove()

        # If node is the goal (target person), then we return a solution
        if node.state == target:
            movies = []
            persons = []
            while node.parent is not None:
                movies.append(node.action)
                persons.append(node.state)
                node = node.parent
            movies.reverse()
            persons.reverse()

            solution = []
            for i in range(len(movies)):
                solution.append((movies[i], persons[i]))
            return solution

        # Mark node as explored
        explored.add(node.state)

        # Add neighbors to frontier
        for (movie_id, person_id) in neighbors_for_person(node.state):
            if not frontier.contains_state(
                    person_id) and person_id not in explored:
                child = Node(state=person_id, parent=node, action=movie_id)
                frontier.add(child)
Ejemplo n.º 14
0
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.
    """
    # TODO
    # Initialize frontier to just the starting position
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    states_in_frontier = set()
    frontier.add(start)
    states_in_frontier.add(source)

    # Initialize an empty explored set
    explored = set()

    # Keep looping until solution found
    while True:
        # If nothing left in frontier, then no path
        if frontier.empty():
            return None

        # Choose a node from the frontier
        node = frontier.remove()
        states_in_frontier.remove(node.state)

        # Mark node as explored
        explored.add(node.state)

        # Add neighbors to frontier
        set1 = neighbors_for_person(node.state)
        for action, state in set1:
            if state not in explored and state not in states_in_frontier:
                child = Node(state=state, parent=node, action=action)

                # If node is the goal, then we have a solution
                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()
                    # Form the list with (movie_id, person_id) pairs, as required
                    solution = []
                    length = len(actions)
                    for i in range(length):
                        solution.append((actions[i], cells[i]))
                    return solution

                frontier.add(child)
                states_in_frontier.add(child.state)
Ejemplo n.º 15
0
class UI:
    def __init__(self):
        self._root = Node()

    def add_widget(self, obj):
        self._root.add_child(obj)

    @property
    def root(self):
        return self._root
Ejemplo n.º 16
0
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.
    """

    """Finds a solution to maze, if one exists."""

    # Keep track of number of states explored
    num_explored = 0
    
    # Initialize frontier to just the starting position
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)
    
    # Initialize an empty explored set
    explored = set()
    
    # Keep looping until solution found
    while True:
    
    # If nothing left in frontier, then no path
        if frontier.empty():
            raise Exception("no solution")
        
        # Choose a node from the frontier
        node = frontier.remove()
        num_explored += 1
        
        # If node is the goal, then we have a solution
        if node.state == target:
            actions = []
            cells = []
            path = []
            while node.parent is not None:
                path.append((node.action, node.state))
                #actions.append(node.action)
                #cells.append(node.state)
                node = node.parent
            #actions.reverse()
            #cells.reverse()
            path.reverse()
            return path
        
        # Mark node as explored
        explored.add(node.state)
        
        # Add neighbors to frontier
        for action, state in neighbors_for_person(node.state):
            if not frontier.contains_state(state) and state not in explored:
                child = Node(state=state, parent=node, action=action)
                frontier.add(child)
Ejemplo n.º 17
0
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.
    """

    # Initialize frontier to just the source name
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # Initialize an empty explored set
    explored = set()

    # Keep looping until solution
    while True:

        # If nothing left in frontier, then no path
        if frontier.empty():
            raise Exception('No solution.')

        # Choose node from the frontier
        node = frontier.remove()
        #print(people[node.state]['name'])
        explored.add(node.state)
        #print(explored)

        # If node is the goal, then we have a solution
        if node.state == target:
            solution = []
            while node.parent is not None:
                path = (node.action, node.state)
                solution.append(path)
                node = node.parent
            solution.reverse()
            #print(solution)
            return solution

        # Add neighbors to the frontier
        for action, state in neighbors_for_person(node.state):
            if not frontier.contains_state(state) and state not in explored:
                if state == target:
                    solution = []
                    node = Node(state=state, action=action, parent=node)
                    while node.parent is not None:
                        path = (node.action, node.state)
                        solution.append(path)
                        node = node.parent
                    solution.reverse()
                    #print(solution)
                    return solution
                child = Node(state=state, action=action, parent=node)
                frontier.add(child)
Ejemplo n.º 18
0
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.
    """

    # A variable that keep track of number of states explored (OPTIONAL)
    num_explored = 0

    # Set the state in which the agent begins and the goal.
    start = Node(state=source, parent=None, action=None)
    goal = target

    # Initialize a frontier that contains the initial state.
    frontier = QueueFrontier()
    frontier.add(start)

    # Initialize an empty explored set
    explored = set()

    while True:
        # Checks if the frontier is empty
        if frontier.empty():
            return None

        # Add a node to the explored set.
        node = frontier.remove()
        explored.add(node.state)

        # Add one each time a state is explored
        num_explored += 1

        # Expand node, add resulting nodes to the frontier
        # if they aren't already in the frontier or the explored set.
        # Also checks if a child node contains the goal state
        for action, state in neighbors_for_person(node.state):
            if not frontier.contains_state(state) and (state not in explored):
                child = Node(state=state, parent=node, action=action)

                if child.state == goal:
                    path = []
                    node = child
                    while node.parent is not None:
                        path.append((node.action, node.state))
                        node = node.parent

                    #Print the number of states explored (OPTIONAL)
                    print(f"States Explored: {num_explored}")

                    path.reverse()
                    return path

                frontier.add(child)
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.
    """

    num_explored = 0

    # Keep track of number of states explored
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # Initialize an empty explored set
    explored = set()

    # Keep looping until you've checked all states
    while True:

        # Emma Watson
        # Ezra Miller
        # Michael Stuhlbarg

        # If nothing left in frontier, then no path
        if frontier.empty():
            return None

        # Choose a node from the frontier
        node = frontier.remove()
        num_explored += 1

        # If node is the goal, then we have a solution
        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()
            return list(zip([int(i) for i in actions],
                            [int(i) for i in cells]))

        # Mark node as explored
        explored.add(node.state)

        # Add neighbors to frontier
        for action, state in neighbors_for_person(
                node.state):  # (movie_id, person_id)
            if not frontier.contains_state(state) and state not in explored:
                child = Node(state=state, parent=node, action=action)
                frontier.add(child)
Ejemplo n.º 20
0
def find_connection(start_id, end_id):
    '''
    Finds and returns the connection between two actors
    '''

    # Keeps track of all ids which have been visited
    visited = set()
    visited.add(start_id)

    # Gets all the stars who are in the same movie as the starting actor
    neighbors = get_neighbors(start_id, visited)
    queue = Queue()
    paths = list()

    # Checking all the neighbors of the start and adds them to the queue
    for movie_id, star_id in neighbors:
        if star_id == end_id:
            return [(movie_id, star_id)]

        if star_id not in visited:
            # Stores each connection between actors
            node = Node(start_id, movie_id, star_id)
            queue.push(node)

            paths.append([(movie_id, star_id)])

    while not queue.isEmpty():
        # Get the current node and add it to the visited set
        current_node = queue.pop()
        current_star_id = current_node.star_2_id
        visited.add(current_star_id)

        # Gets rhe current path
        current_path = paths[0]
        paths = paths[1:]

        neighbors = get_neighbors(current_star_id, visited)

        for movie_id, star_id in neighbors:
            path = list(current_path)
            if star_id not in visited:
                # Adds a star's id to the queue if it has not been visited
                node = Node(current_node.star_2_id, movie_id, star_id)
                queue.push(node)

                path.append((movie_id, star_id))
                paths.append(path)

            # Checks if connection has been found
            if star_id == end_id:
                return path

    # No path
    else:
        return None
Ejemplo n.º 21
0
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.
    """

    num_explored = 0

    starting_node = Node(state=source, parent=None, action=None)
    my_frontier = QueueFrontier()  # frontier
    my_frontier.add(starting_node)  # initial state

    explored_set = set()  # empty explored set

    done = False

    while not done:
        if my_frontier.empty():
            raise Exception("no solution")

        my_node = my_frontier.remove()  # check if empty and removed node from frontier
        num_explored += 1

        if num_explored % 100 == 0:
            print(f"Number Explored: {num_explored}")

        if my_node.state[1] == target:
            parents = []
            while my_node.parent is not None:
                parents.append(my_node.state)
                my_node = my_node.parent
            target = parents
            return target
        explored_set.add(my_node.state)

        try:
            if len(explored_set) == 1:
                for x in neighbors_for_person(my_node.state):
                    if not my_frontier.contains_state(x) and x not in explored_set:
                        child = Node(state=x, parent=my_node, action=None)
                        my_frontier.add(child)

            else:
                for x in neighbors_for_person(my_node.state[1]):
                    if not my_frontier.contains_state(x) and x not in explored_set:
                        child = Node(state=x, parent=my_node, action=None)
                        my_frontier.add(child)

        except KeyError:
            pass

        if my_frontier.empty():
            done = True
Ejemplo n.º 22
0
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.
    """

    # TODO

    # Initialize path as a list
    path = []

    # Initialize a set that contains movie-person pairs which are explored
    person_explored = set()
    num_explored = 0

    # Initialize the frontier to just the starting pair
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # Keep looping until solution found
    while True:

        # if nothing left in frontier, then no solution
        if frontier.empty():
            return None
        
        # Choose a node from the frontier
        node = frontier.remove()
        num_explored += 1

        # If node is the goal, then we have a solution
        if node.state == target:
            actions = []
            people = []
            while node.parent is not None:
                actions.append(node.action)
                people.append(node.state)
                node = node.parent
            actions.reverse()
            people.reverse()
            for i in range(len(actions)):
                path.append((actions[i], people[i]))
            return path

        # Mark pair as explored
        person_explored.add(node.state)

        # Add neighbors to frontier
        for movie, person in neighbors_for_person(node.state):
            if not frontier.contains_state(person) and person not in person_explored:
                child = Node(state=person, parent = node, action = movie)
                frontier.add(child)
Ejemplo n.º 23
0
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 the start node+frontier, and insert the start node
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # list of explored actors
    checkedActors = set()

    while True:
        # If queue is empty, we've checked all actors inserted, and found no connection :-(
        if frontier.empty():
            return None

        # read a node from the queue
        node = frontier.remove()
        #print("working on =",people[node.state])

        # add current actor id to processed actor list - not much sense re-processing the current node...
        checkedActors.add(node.state)

        # Find neighbors of current actor ID
        neighbors = neighbors_for_person(node.state)
        #print(people[node.state]["name"]+" has "+str(len(neighbors))+" actors who played with him/her")

        # check the list of actors
        for movieID, actorID in neighbors:
            #print("actor "+people[actorID]["name"]+"("+actorID+") in movie "+movies[movieID]["title"])

            # if we already processed this actor, skip to the next actor in the list
            if actorID not in checkedActors:
                # create a new node
                child = Node(state=actorID, parent=node, action=movieID)

                # did we reach the "destination" actor?
                if child.state == target:
                    # create the path (movie id, actor id) - it's backwards (from the destination to the source)
                    path = []
                    node = child
                    while node.parent is not None:
                        path.append((node.action, node.state))
                        node = node.parent

                    # reverse the order
                    path.reverse()
                    return path

                # not a the "destination" yet, add the node and move on
                frontier.add(child)
Ejemplo n.º 24
0
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.
    """
    # Keep track of number of states explored
    num_explored = 0

    # Initialize frontier to just the starting position (source)
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # Initialize an empty explored set
    explored_set = set()

    #Keep looping until solution found
    while True:

        #If nothing left in frontier, then no path
        if frontier.empty():
            raise Exception("No Solution")

        # choose a node from the frontier
        node = frontier.remove()
        num_explored += 1

        # Add neighbors to frontier
        for action, state in neighbors_for_person(node.state):
            if not frontier.contains_state(
                    state) and state not in explored_set:

                # If this node is the target, then we have a solution
                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()
                    zip_actionsAndCells = zip(actions, cells)
                    solution = []
                    for temp in zip_actionsAndCells:
                        solution.append(temp)
                    return solution

                child = Node(state=state, parent=node, action=action)
                frontier.add(child)

        # Mark node as explored
        explored_set.add(node.state)
Ejemplo n.º 25
0
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.
    """

    # TODO
    # Start with empty frontier and explored set
    # Add frontier nodes
    # If frontier is empty, no solution
    # Remove node from frontier
    # If node is goal, success
    # Add node to explored
    # If not in frontier or explore set, expand node
    # If daughter node is not goal, add to frontier

    explored = set()
    frontier = QueueFrontier()

    start = Node(state=source, parent=None, action=None)
    frontier.add(start)

    while True:
        if frontier.empty():
            return None
        
        node = frontier.remove()

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

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

            actions.reverse()
            states.reverse()
            solution = list(zip(actions, states))

            return solution

        explored.add(node.state)

        for action, state in neighbors_for_person(node.state):
            if not frontier.contains_state(state) and state not in explored:
                child = Node(state=state, parent=node, action=action)
                frontier.add(child)


    
    raise NotImplementedError
Ejemplo n.º 26
0
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.
    """

    #Setup the frontier
    Frontier = QueueFrontier()
    InitialNode = Node(state=source, parent=None, action=None)
    Frontier.add(InitialNode)
    ExploredStates = []

    #Check the node
    while True:

        #If it's empty, there's no solution
        if Frontier.empty():
            raise Exception("No solution")

        #Remove one then consider it
        nodeToCheck = Frontier.remove()

        #Is it the goal state? then return
        if nodeToCheck.state == target:
            path = []
            #(Movie ID to get there from previous, person id)

            #loop and add the path to the array
            while nodeToCheck.parent is not None:
                path.append((nodeToCheck.action, nodeToCheck.state))
                nodeToCheck = nodeToCheck.parent

            #return it
            path.reverse()
            return path

        else:

            #else, add it to the  explored states and get its neighbors to add them to the frontier

            ExploredStates.append(nodeToCheck.state)
            neighbors = neighbors_for_person(nodeToCheck.state)

            for movie_id, person_id in neighbors:
                if not Frontier.contains_state(
                        person_id) and person_id not in ExploredStates:
                    Frontier.add(
                        Node(state=person_id,
                             parent=nodeToCheck,
                             action=movie_id))

    # TODO
    raise NotImplementedError
Ejemplo n.º 27
0
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.
    """
    '''
    node should contain state: movie_i, 
                        parent = movie_j , 
                        action: co-starring person id that lead from Movie i to movie j 
    # first, put all neighbours for source person into queue, check for goal before putting them in
    # take the next state in queue, check goal, if not, find all neighbours in queue, repeat. 
    '''

    # TODO
    # Keep track of number of movies explored
    num_explored = 0
    # Initialize frontier to just the starting position
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)
    # Initialize an empty explored set for person
    explored = set()

    # keeo looping until solution found
    while True:
        # if nothing left in the frontier, then no solution
        if frontier.empty():
            path = None

        # choose a node from the frontier
        node = frontier.remove()
        num_explored += 1

        #print(node.state)

        # if node is the goal, then we have a solution
        if node.state == target:
            path = get_path(node)
            return path

        # Mark person as explored
        explored.add(node.state)

        # Add neighbors to frontier (check goal first)
        for movie_id, person_id in neighbors_for_person(node.state):
            if person_id == target:
                child = Node(state=person_id, parent=node, action=movie_id)
                path = get_path(child)
                return path
            elif not frontier.contains_state(
                    person_id) and person_id not in explored:
                child = Node(state=person_id, parent=node, action=movie_id)
                frontier.add(child)
Ejemplo n.º 28
0
def shortest_path(source, target):
    """
    Returns the shortest list of (movie_id, person_id) pairs
    that connect the source to the target.
    """
    neighbours_for_x = neighbors_for_person(source) 
    frontier = QueueFrontier()
    print("the source is: "+ source)
    print("the target is: "+ target)
    
    node_list = []
    node_hist = []
    movie_people_seen = []
    action_start= 0

    #adding nodes to the queue to loop over.
    for every in neighbours_for_x:
        current_node = Node(state=every, parent=("",source),action= action_start)
        frontier.add(current_node)


    #loop until we have found a link otherwise return none if the queue is empty.   
    while True: 
        if frontier.empty():
            return None

        #getting item from queue, adding the removed item to list of seen nodes.
        node = frontier.remove()
        node_hist.append((node.state[0],node.state[1],node.parent[0],node.parent[1]))
        movie_people_seen.append((node.state[0],node.state[1]))

        if node.state[1] == target:
            print("link found")
            node_list.append(node.state)

            #creating the list of nodes we passed through from source to get to the target.
            for every in node_hist:
                if every[0] == node.parent[0] and every[1] == node.parent[1]:
                    node_list.append((every[0], every[1]))
                    node = Node(state=(every[0],every[1]), parent=(every[2],every[3]), action = action_start)
                    if every[3] == source:
                        break
                        
            #returning the list.
            return node_list[::-1]

        node_neighbours = neighbors_for_person(node.state[1])
        #looping over neighbours if we didn't find a connection to the target yet.
        for every in node_neighbours:
            if every not in movie_people_seen:
                #keeping track of the depth of our search.
                action_new_number = node.action + 1 
                node_current = Node(state = every, parent= node.state, action= action_new_number)
                frontier.add(node_current)
Ejemplo n.º 29
0
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.
    """

    # note that 'action' here refers to movie_id
    source_node = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(source_node)
    # Initialize number of explored states and explored nodes set
    states_explored = 0
    nodes_explored = set()
    while True:

        # Stop if nothing to explore and thus no path found
        if frontier.empty():
            raise Exception("no solution")

        # Picking shallowest node, using queue
        node = frontier.remove()
        states_explored += 1

        # Check if node is goal and return if goal
        if node.state == target:
            path = []
            print("1", node.state)
            while node.parent is not None:
                path.append((node.action, node.state))
                node = node.parent
            path.reverse()
            return path

        # Record node explored
        nodes_explored.add(node.state)

        for action, state in neighbors_for_person(node.state):
            # checking node as they're added to frontier
            if state == target:
                path = []
                path.append((action, state))
                while node.parent is not None:
                    path.append((node.action, node.state))
                    node = node.parent
                path.reverse()
                return path

            # add neighbors to frontier
            elif not frontier.contains_state(
                    state) and state not in nodes_explored:
                child = Node(state=state, parent=node, action=action)
                frontier.add(child)
Ejemplo n.º 30
0
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.
    """
    # Initialize frontier to just the starting position
    start = Node(state=source, parent=None, action=None)
    frontier = QueueFrontier()
    frontier.add(start)

    # Initialize an empty explored set
    explored = set()
    solution = []

    # Keep track of number of states explored
    num_explored = 0

    # Keep looping until solution found
    while True:

        # If nothing left in frontier, then no path
        if frontier.empty():
            return None

        # Choose a node from the frontier
        node = frontier.remove()
        num_explored += 1

        # to prevent endless run
        if num_explored > 200:
            sys.exit("couldn't find quick solution")

        # Mark node as explored
        explored.add(node.state)

        # Add neighbors to frontier
        neighbors = neighbors_for_person(node.state)
        for action, state in neighbors:
            if not frontier.contains_state(state) and state not in explored:
                # If node is the goal, then we have a solution
                if state == target:
                    # Add current/last connection to the goal person
                    solution.append([action, state])
                    # Add all previous connections using parent nodes
                    while node.parent is not None:
                        solution.append([node.action, node.state])
                        node = node.parent
                    solution.reverse()
                    print(f"{num_explored} nodes were explored.")
                    return solution
                child = Node(state=state, parent=node, action=action)
                frontier.add(child)