Beispiel #1
0
def earliest_ancestor(ancestors, starting_node):
    """
    given the dataset and the ID of an individual in the dataset, 
    returns their earliest known ancestor – 
    the one at the farthest distance from the input individual. 
    If there is more than one ancestor tied for "earliest", 
    return the one with the lowest numeric ID. 
    If the input individual has no parents, the function should return -1.
    """
    # Instantiate graph, count and way to track final vertex
    graph = Graph()
    final_v = 0
    total_counter = 0

    # for people in ancestors
    # add vertex and edge
    for people in ancestors:
        graph.add_vertex(people[0])
        graph.add_vertex(people[1])

    for people in ancestors:
        graph.add_edge(people[1], people[0])

    # Instantiate Stack() to hold nodes to visit
    to_visit = Stack()
    to_visit.push(starting_node)

    # set to hold visited
    visited = set()

    # if not ancestors return -1
    # no ancestors means no neighbors so it must be own ancestor
    # -1 for being your own ancestor ... lol hillbilly - I am my own grandpa
    if len(graph.get_neighbors(starting_node)) == 0:
        return -1

    count = 0
    # so long as we have vertex to visit start popping
    while to_visit.size() > 0:
        vertex = to_visit.pop()

        if len(graph.get_neighbors(vertex)) == 0:
            if count > total_counter:
                total_counter = count
                final_v = vertex
            if count == total_counter:
                if vertex < final_v:
                    final_v = vertex

        if vertex not in visited:
            visited.add(vertex)

            if len(graph.get_neighbors(vertex)) != 0:
                for next_v in graph.get_neighbors(vertex):
                    to_visit.push(next_v)
                count += 1
            else:
                if to_visit.size() == 0:
                    return final_v
Beispiel #2
0
def earliest_ancestor(ancestors, starting_node):
    '''
    Build the graph
    '''
    # instantiate a new graph object
    graph = Graph()
    # loop over all pairs in ancestors
    for pair in ancestors:
        # add pair[0] and pair[1] to the graph
        graph.add_vertex(pair[0])
        graph.add_vertex(pair[1])
        # build the edges in reverse
        graph.add_edge(pair[1], pair[0])
    '''
    BFS with paths to find the earliest known ancestor
    '''
    # create a queue
    queue = Queue()
    # enqueue starting node inside a list
    queue.enqueue([starting_node])
    # set a max path length to 1
    max_path_length = 1
    # set initial earliest ancestor
    earliest_ancestor = -1
    # while the queue is not empty
    while not queue.is_empty():
        # dequeue to the path
        path = queue.dequeue()
        # set a vertex to the last item in the path
        vertex = path[-1]
        # if path is longer or equal and the value is smaller, or if the path is longer
        if (len(path) >= max_path_length and
                vertex < earliest_ancestor) or (len(path) > max_path_length):
            # set the earliest ancestor to the vertex
            earliest_ancestor = vertex
            # set the max path length to the len of the path
            max_path_length = len(path)
        # loop over next vertex in the set of vertices for the current vertex
        for next_vertex in graph.vertices[vertex]:
            # set a new path equal to a new list of the path
            path_copy = list(path)
            # append next vertex to new path
            path_copy.append(next_vertex)
            # enqueue the new path
            queue.enqueue(path_copy)
    # return earliest ancestor
    return earliest_ancestor
Beispiel #3
0
def earliest_ancestor(ancestors, current_vertex):
    # create blank graph for ancestors
    current_graph = Graph()
    # loop through and add all ancestors
    for ancestor in ancestors:
        current_graph.add_vertex(ancestor[0])
        current_graph.add_vertex(ancestor[1])
    # loop through and add all edges
    for ancestor in ancestors:
        current_graph.add_edge(ancestor[1], ancestor[0])

    max_path = 1
    # if the input has no parents return -1
    earliest_ancestor = -1
    # create blank traversing path
    traversing_path = Stack()
    # Start traversing path with the first vertex
    traversing_path.push([current_vertex])

    # while traversing path not empty
    while traversing_path.size() > 0:
        # start traversed path
        traversed_path = traversing_path.pop()
        # get last vertex in the traversed path
        last_vertex = traversed_path[-1]
        # get length of traversed path
        tp_length = len(traversed_path)
        # (if traversed path is longer than or equal to max_path AND
        # if last vertex is smaller than current earliest ancestor )
        # ##### OR
        # if traversed path is longer than max_path
        if (tp_length >= max_path
                and last_vertex < earliest_ancestor) or (tp_length > max_path):
            # set earliest ancestor as last vertex
            # set max path as last item in traversed path
            earliest_ancestor = last_vertex
            max_path = len(traversed_path)
        # get neighbors of last vertex
        neighbors = current_graph.vertices[last_vertex]
        # loop through each neighbor
        for neighbor in neighbors:
            # get current path list, append neighbor to it, and add to traversing path
            new_path = list(traversed_path)
            new_path.append(neighbor)
            traversing_path.push(new_path)
    # return earliest ancestor
    return earliest_ancestor
Beispiel #4
0
def earliest_ancestor(ancestors, starting_node):
    ancestorTree = Graph()
    # Iterate through ancestors to find vertices
    # for (parent,child) in ancestors
    for ancestor in ancestors:
        for vert in ancestor:
            ancestorTree.add_vertex(vert)
    # print("Tree", ancestorTree.vertices)

    for ancestor in ancestors:
        ancestorTree.add_edge(ancestor[1], ancestor[0])
    # print("Tree", ancestorTree.vertices)

    # default length to check the length of path list against
    longest_path = 1
    # counter for storing storing the last node
    last_node = 0
    # passing the vertices by reference
    ancestor_vert = ancestorTree.vertices

    # Iterate through the vertices of the ancestorTree
    for i in ancestor_vert:
        # i = individual nodes/vertices added using add_vert()
        # returns a list of nodes and sets the list to the variable path
        path = ancestorTree.dfs(starting_node, i)
        # print("path list loop", path)

        # If path is not = to None and the length of the path list in greater that longest_path which defaults to the value integer 1
        if path is not None and len(path) > longest_path:
            # set longest_path = length of the path
            longest_path = len(path)
            print("longest_path", longest_path)
            # last node is = to last node/vertice of the longest_path
            last_node = i
            print("last_node", last_node)
        # I was missing that longest_path defaults to 1.
        # If path list is empty and longest_path is set to default of 1
        elif not path and longest_path == 1:
            # print("empty", path)
            # print("elif path", longest_path)
            # set last_node to -1
            last_node = -1

    # print("Out of for loop", last_node)
    return last_node
Beispiel #5
0
def earliest_ancestor(ancestors, starting_node):
    graph = Graph()

    # Add vertices
    for i in ancestors:
        if i[0] not in graph.vertices:
            graph.add_vertex(i[0])
        if i[1] not in graph.vertices:
            graph.add_vertex(i[1])

    # Add edges
    for i in ancestors:
        graph.add_edge(i[1], i[0])

    path = graph.bft(starting_node)
    oldest = path[-1]

    if starting_node == oldest:
        return -1
    else:
        return oldest
Beispiel #6
0
def earliest_ancestor(ancestors, starting_node):
    graph = Graph()
    for parent, child in ancestors:
        vertices = graph.vertices
        if parent not in vertices:
            graph.add_vertex(parent)
        if child not in vertices:
            graph.add_vertex(child)
        graph.add_edge(child, parent)

    s = Stack()
    s.push([starting_node])

    longest = [starting_node]
    visited = set()
    oldest = -1

    while s.size() > 0:
        path = s.pop()
        curr = path[-1]
        # breakpoint()
        if (len(path) > len(longest)) or (len(path) == len(longest)
                                          and curr < oldest):
            longest = path
            oldest = longest[-1]

        if curr not in visited:
            visited.add(curr)

            parents = graph.get_neighbors(curr)

            for parent in parents:
                new_path = path + [parent]
                s.push(new_path)

    return oldest
Beispiel #7
0
def earliest_ancestor(ancestors, starting_node):
    ancestor_tree = Graph()
    # Iterate through ancestors
    for (parent, child) in ancestors:
        # Add vertices to ancestor_tree
        ancestor_tree.add_vertex(parent)
        ancestor_tree.add_vertex(child)
    # print("ancestor tree", ancestor_tree.vertices)

    for (parent, child) in ancestors:
        # Add edges
        ancestor_tree.add_edge(child, parent)
    # print("neighbors", ancestor_tree.get_neighbors(5))
    # print("ancestor tree", ancestor_tree.vertices)

    longest_path = 1  # Keep track of # ancestors; highest means most ancestors
    earliest_ancestor = 0  # Store last node (as an integer)
    for i in ancestor_tree.vertices:
        # print("i", i)  # Print vertices
        # Call dfs function from Graph class
        path = ancestor_tree.dfs(
            i, starting_node)  # i is each vertex/node in graph
        # print("ancestor dfs", ancestor_tree.dfs(starting_node, i))
        print('path', path)
        if path:  # If there are items in list
            if len(
                    path
            ) > longest_path:  # If list length is greater than longest path
                longest_path = len(
                    path)  # Set longest path equal to list length
                earliest_ancestor = i  # Set earliest_ancestor equal to current node/vertex
        elif not path and longest_path == 1:  # If path is 'None' and 'longest_path' is our default of 1
            earliest_ancestor = -1

    print("earliest ancestor", earliest_ancestor)
    return earliest_ancestor
Beispiel #8
0
while True:
    room = player.currentRoom

    # Mark room down as visited and identified
    identified_rooms.add(room.id)
    visited_rooms.add(room.id)
    # path_by_ids.append(room.id)
    graph.add_vertex(room.id)

    # Make note of all of the exits of a room
    for direction in room.getExits():
        adjacent_room_id = room.getRoomInDirection(direction).id
        identified_rooms.add(adjacent_room_id)
        graph.add_vertex(adjacent_room_id)
        graph.add_edge(room.id, adjacent_room_id, direction)

    # If room has been visited before, stop
    if identified_rooms == visited_rooms:
        break

    # Search for all the directions to rooms we haven't visited yet.
    def findUnvisitedRooms(room_object):
        return [direction for direction, ID in graph.vertices[room_object.id].items() if ID not in visited_rooms]

    unvisited_directions = findUnvisitedRooms(room)

    # Find all directions to rooms that still have directions not used
    revisited_directions = []
    for direction in graph.vertices[room.id].keys():
        neighbor = room.getRoomInDirection(direction)
    'dl\n', 'format=edgelist1\n', 'n=5\n', 'data:\n', '1 3 78.250\n',
    '2 3 76.750\n', '3 5 63.500\n', '3 2 51.250\n', '3 1 62.875\n',
    '4 3 13.625\n', '4 2 1.625\n', '4 1 14.125\n', '5 2 10.875\n', '5 1 40.000'
]

#Inicializando as arestas e o número de vértices:
edges, n = getInsert(ins)

#Criando os vértices:
vertices = [v for v in range(1, (n + 1))]

graph = Graph()

#Populando os nós do Grafo:
for v in vertices:
    graph.add_node(v)

#Populando as arestas do Grafo:
for e in edges:
    graph.add_edge(e[1], e[2], e[0])

#Executando Dijkstra:
visited, path = dijsktra(graph, 1)

#Imprimindo o resultado:
for vertex in graph.nodes:
    try:
        print(vertex, "%.3f" % float(visited[vertex]))
    except Exception:
        print(vertex, "INFINITO")
visited = set()
# Continue until we have seen all rooms and the stack is empty
while stack.size() > 0:
    room = stack.pop()  # returns a <Room> class instance, not a room id
    room_id = room.id
    if room_id not in graph.vertices:
        graph.add_vertex(room_id)
    # Get connected rooms
    connected_rooms = room.get_exits()  # returns an array of directions
    for direction in connected_rooms:
        connected_room = room.get_room_in_direction(
            direction)  # returns a <Room> class instance
        connected_room_id = connected_room.id
        if connected_room_id not in graph.vertices:
            graph.add_vertex(connected_room_id)
        graph.add_edge(room_id, connected_room_id, direction)
        # After making the connection in the graph add it to the stack
        if connected_room_id not in visited:
            stack.push(connected_room)
    visited.add(room_id)


# NEXT: Use the graph to find the most efficient route that visits all rooms at least once
def find_next_path(room_id, visited, g=graph):
    """
    Takes in a room id and a set of visited room ids

    returns a set of moves that the player can take to get to the nearest unvisited space.
    """
    rooms_with_moves = {}  # [ ["LIST OF ROOM IDS"], ["LIST OF MOVES"] ]
    rooms_with_moves[room_id] = [[room_id], []]
Beispiel #11
0
        print(response)
        exits = {}
        for d in response["exits"]:
            exits[d] = '?'

        exits[dir_reverse[direction]] = last_room_id

        if response["room_id"] not in explored_rooms:
            world_graph.add_vertex(response["room_id"], response["title"],
                                   response["description"],
                                   response["coordinates"],
                                   response["elevation"], response["terrain"],
                                   response["items"], exits,
                                   response["messages"])

        world_graph.add_edge(last_room_id, direction, response["room_id"])

        cooldown = response["cooldown"]
        time.sleep(cooldown + 1)
        explored_rooms.add(response["room_id"])
        # r = Timer(cooldown + 1, add_explored, (explored_rooms,response["room_id"]))
        # r.start()
        last_room_id = response["room_id"]
    else:
        path = world_graph.unexplored_search(last_room_id)
        modified_path = []
        for index, i in enumerate(path):
            if index < len(path) - 1:
                current = i
                after = path[index + 1]