예제 #1
0
class MyQueue:
    def __init__(self):
        self.front = Stack()
        self.end = Stack()

    def size(self):
        return self.front.size() + self.end.size()

    def enqueue(self, val):
        self.end.push(val)

    def dequeue(self):
        if self.front.is_empty() and not self.move():
            raise Exception("queue is empty")
        return self.front.pop()

    def peek(self):
        if self.front.is_empty() and not self.move():
            raise Exception("queue is empty")
        return self.front.peek()

    # time: O(n), however, the average is O(1)
    def move(self):
        moved = False
        while not self.end.is_empty():
            moved = True
            self.front.push(self.end.pop())
        return moved

    def print_q(self):
        print self.front
        print self.end
예제 #2
0
    def dft(self, starting_vertex: T) -> None:
        """
        Print each vertex in depth-first order
        beginning from starting_vertex.
        """
        # keep track of visited vertices
        visited = set()
        # create a stack class
        stack = Stack()
        # push the starting vertex onto the stack
        stack.push(starting_vertex)

        # while stack is not empty
        while stack.size():
            # pop from the stack
            current_vertex = stack.pop()

            # if current vertex has not been visited
            if current_vertex not in visited:
                # add it to visited
                visited.add(current_vertex)
                # print the current vertex
                print(current_vertex)

                # for every neighbors of current_vertex
                for vertex in self.vertices[current_vertex]:
                    # push it onto the stack
                    stack.push(vertex)
예제 #3
0
 def dfs(self, starting_vertex, destination_vertex):
     """
     Return a list containing a path from
     starting_vertex to destination_vertex in
     depth-first order.
     """
     # make a stack
     stack = Stack()
     # make a visited set
     visited = set()
     # push the PATH to that node
     stack.push([starting_vertex])
     # while the stack isn't empty
     while stack.size():
         # pop the PATH
         path = stack.pop()
         # the last thing in the path is our current item
         node = path[-1]
         # if node is not visited:
         if node not in visited:
             # CHECK if it is the target
             if node == destination_vertex:
                 return path
             visited.add(node)
             for neighbor in self.vertices[node]:
                 #copy the path
                 PATH_COPY = path.copy()
                 # add neighbor to the path
                 PATH_COPY.append(neighbor)
                 # enqueue the PATH_COPY
                 stack.push(PATH_COPY)
     return None
예제 #4
0
def earliest_ancestor(ancestors, starting_node, visited=None, path=None):

    # initialize path = [starting_node]
    # path = [starting_node]
    # get parents - only care about parent not starting node i.e: node[1]
    # loop to check for number of connections
    # if no connections return -1

    print('ancestors:', ancestors)
    print('starting_node:', starting_node)

    graph = Graph()
    stack = Stack()
    path = [starting_node]
    stack.push(path)

    graph = {}
    for key, value in ancestors:
        # print('k,v:',key, value)
        if value not in graph:
            # print('aa',value)
            graph[value] = set()
        if key not in graph:
            print('aa', value)
            graph[key] = set()
        graph[value].add(key)

    print('graph:', graph)
    if len(graph[starting_node]) == 0:
        return -1
    visited = set()
    paths = list()
    print('paths:', paths)

    while stack.size() > 0:
        current_path = stack.pop()
        print('current_path:', current_path)
        current_node = current_path[-1]
        print('current_node:', current_node)

        if current_node not in visited:
            visited.add(current_node)
            print('visited', visited)

            for parent in graph[current_node]:
                if parent not in visited:
                    new_path = list(current_path)
                    new_path.append(parent)
                    print('new_path:', new_path)
                    stack.push(new_path)
            if len(graph[current_node]) == 0:
                paths.append(current_path)
                print('paths:', paths)
    sorted_paths = sorted(paths, reverse=True)  # key=lambda x: len(x))
    print('*****', sorted_paths[-1][-1])
    return sorted_paths[-1][-1]
예제 #5
0
def path(starting_point):
    graph = dft(player)

    visited = {}
    visits = {}

    if graph:

        s = Stack()
        s.push([starting_point.current_room.id])

        while s.size() > 0:
            path = s.pop()
            current_room = path[-1]
            count = 0
            random_direction = ''

            if current_room in visited:
                get_list = len(traversal_path)
                print(get_list)
            if len(visited) < 9:
                visited[current_room] = path
                randoms = []
                for idx, val in graph[current_room].items():

                    if val is not '?':
                        randoms.append(idx)
                        random_direction = random.choice(randoms)

                if len(random_direction) == 1:
                    if len(traversal_path) == 0:
                        traversal_path.append(random_direction)
                        get_new_room = graph[current_room][random_direction]
                        s.push([get_new_room])
                        random_direction = ''

                    else:
                        traversal_path.append(random_direction)
                        get_new_room = graph[current_room][random_direction]
                        s.push([get_new_room])
                        random_direction = ''

                    # for next_position in graph:

                    #     s.push([next_position])

        print(len(traversal_path), "TRAVERSAL PATH LENGTH")
        print(len(visited), "LENGTH VISITED")
        print(graph, "GRAPH")
        return traversal_path
예제 #6
0
    def dft(self, starting_vertex):
        """
        Print each vertex in depth-first order
        beginning from starting_vertex.
        """
        # make a stack
        s = Stack()
        # push on your starting node
        s.push([starting_vertex])
        # make a set to track if it was visited
        visited = set()
        # while stack not empty
        while s.size() > 0:
            # pop off what is on top.
            current_node = s.pop()
            # if we have no visited the vertex before
            if current_node not in visited:
                # run function/print
                # print(current_node)
                # mark as visited
                # visited.add(current_node)
                # get its neighbors
                # neighbors = self.get_neighbors(current_node)
                # for each of the neighbors

                self.vertices[room.id] = {}
                for neighbor in room.get_exits():
                    self.vertices[room.id][room.get_room_in_direction(
                        possible_direction).id] = neighbor

                visited.add(room)
                exits = room.get_exits()
                while len(exits) > 0:
                    # select first neighbors on list
                    direct = exits[0]
                    # beej: create neighbor object
                    path = list(current_node)
                    # add possibles directions to move
                    path.append(room.get_room_in_direction(direct))
                    # add to stack
                    s.push(path)
                    # remove to contine
                    exits.remove(direct)
        return self.vertices
예제 #7
0
    def dfs(self, starting_vertex: T, destination_vertex: T) -> PathType:
        """
        Return a list containing a path from
        starting_vertex to destination_vertex in
        depth-first order.
        """
        # create the stack class
        stack = Stack()
        # would keep track of visited vertices
        visited = set()
        # push the starting vertex as a list of vert
        stack.push([starting_vertex])

        # while stack is not empty
        while stack.size():
            # pop a path from the stack
            path = stack.pop()
            # get the last vertex from the stack
            current_vert = path[-1]

            # if current_vert is the destination_vertex
            if current_vert == destination_vertex:
                # return path
                return path

            # if current_vert is not in visited:
            if current_vert not in visited:
                # add it to visited
                visited.add(current_vert)

                # for every neighbors of of current_vert
                for vertex in self.vertices[current_vert]:
                    # create a copy of the path
                    new_path = list(path)
                    # append the current vertex
                    new_path.append(vertex)
                    # push the new path onto the stack
                    stack.push(new_path)
예제 #8
0
 def dft(self, starting_vertex):
     """
     Print each vertex in depth-first order
     beginning from starting_vertex.
     """
     # make a stack
     stack = Stack()
     # make a visited set
     visited = set()
     # put starting vertex in the stack
     stack.push(starting_vertex)
     # while the stack isn't empty
     while stack.size():
         # Pop off the top of the stack, it is current item
         node = stack.pop()
         # if node isn't visited
         if node not in visited:
             print(node)
             # mark as visited
             visited.add(node)
             # for each of our current item's edges
             for edge in self.vertices[node]:
                 stack.push(edge)
예제 #9
0
def dft(starting_position):
    """
    Print each vertex in depth-first order
    beginning from starting_vertex.
    """
    # Create a queue/stack as appropriate
    stack = Stack()
    # Put the starting point in that
    stack.push(starting_position.current_room)
    # Make a set to keep track of where we've been
    visited = {}

    # While there is stuff in the queue/stack
    while stack.size() > 0:
        #    Pop the first item
        position = stack.pop()
        #    If not visited
        if position.id not in visited:
            #       DO THE THING!
            exits = position.get_exits()
            visited[position.id] = {'n': '?', 's': '?', 'w': '?', 'e': '?'}
            for exit in exits:
                for idx, val in visited[position.id].items():
                    if idx == exit:
                        if idx == 'n':
                            visited[position.id][idx] = position.n_to.id
                        if idx == 's':
                            visited[position.id][idx] = position.s_to.id
                        if idx == 'e':
                            visited[position.id][idx] = position.e_to.id
                        if idx == 'w':
                            visited[position.id][idx] = position.w_to.id

            for next_position in world.rooms:
                stack.push(world.rooms[next_position])

    return visited
예제 #10
0
class DbSession(object):
    """Provides an API for users to make changes to an in-memory database with transactions.

    Attributes:
        database: An instance of an in-memory database.
        transaction_stack: A stack of active transactions.
        current_trans: The currently active transaction. Transactions are a set of keys which
            represent keys in the database that have been edited during the current transaction.
    """
    def __init__(self):
        self.database = InMemoryDatabase()
        self.transaction_stack = Stack()
        self.current_trans = None
        self.reset_transaction_state()

    def reset_transaction_state(self):
        self.current_trans = set() if self.transaction_stack.is_empty(
        ) else self.transaction_stack.current()
        # Transaction stack should always have a 'base' transaction which can't be rolled back/commited
        self.transaction_stack = Stack(self.current_trans)

    def pop_transaction(self):
        self.transaction_stack.pop()
        self.current_trans = self.transaction_stack.current()

    def has_open_transaction(self):
        return self.transaction_stack.size() > 1

    def begin(self):
        self.current_trans = set()
        self.transaction_stack.push(self.current_trans)

    def rollback(self):
        if not self.has_open_transaction():
            print('NO TRANSACTION')
        else:
            map(self.database.remove, list(self.current_trans))
            self.pop_transaction()

    def commit(self):
        if not self.has_open_transaction():
            print('NO TRANSACTION')
        else:
            self.database.flatten()
            self.reset_transaction_state()

    def set_var(self, var, value):
        if var in self.current_trans:
            self.database.change(var, value)
        else:
            self.database.add(var, value)
            self.current_trans.add(var)

    def unset_var(self, var):
        self.set_var(var, None)

    def get_var(self, var):
        print(self.database.get(var) or 'NULL')

    def num_equal_to(self, value):
        print(self.database.num_equal_to(value))

    def __repr__(self):
        return '{}\nTransaction Stack: {}'.format(self.database,
                                                  self.transaction_stack)
예제 #11
0
def explore(player, db, db_id):
    s = Stack()
    local_visited = set()
    visited_ids = set()
    print(f'EXPLORING THE MAP')

    init_room = player.initalize()
    print(f'Initial room: {init_room}')
    time.sleep(init_room["cooldown"])
    # save room in db
    db.insert_room(init_room)

    for direction in init_room["exits"]:
        s.push({str(init_room["room_id"]): direction})

    db.update_stack(player, s.get_stack())

    # STOP conditon == empty local stack and global que
    while s.size() > 0:
        current_room = s.pop()
        current_room_id = list(current_room.keys())[0]
        current_room_dir = current_room[current_room_id]

        visited_ids.add(current_room_id)
        print(f"Visited {len(visited_ids)} rooms")
        print(
            f'### Currently in room {current_room_id} moving to {current_room_dir} ###')
        if str(current_room) not in local_visited:
            local_visited.add(str(current_room))

            # Make request for next movement
            global_map = db.get_map(db_id)

            if current_room_id not in global_map:
                global_map[current_room_id] = {}
            cur_room_dirs = global_map[current_room_id]

            # check whether the next dir exists on the db map
            if current_room_dir in cur_room_dirs:
                next_room = player.wise_explore(
                    current_room_dir, cur_room_dirs[current_room_dir])
            else:
                # otherwise just use move
                next_room = player.move(current_room_dir)

            print(f'Next room: {next_room}')
            # save next_room in DB
            db.insert_room(next_room)
            print('Going to sleep')
            time.sleep(next_room["cooldown"])
            # update map with newly discovered directions
            update_map(current_room, next_room, db, db_id)

            # check if next room is a shop and save it in DB if it is
            shop_check(next_room, player, db, db_id)

            # check for treasure
            treasure_check(next_room, player, db, db_id)

            # change name room
            if next_room["room_id"] == 467:
                print(f"Found Pirate Ry's name changer")
                names = {"player55": "pavol", "player52": "diana", "player54": "markm", "player53": "talent antonio"}

                if player["name"] in names:
                    res = player.change_name(names[player["name"]])
                    print(f"Changed name: {res}")
                    time.sleep(res["cooldown"])

            # shrine room
            if next_room["room_id"] == 22:
                print("Found Shrine!")
                i_pray = player.pray()
                print(f"You prayed at the shrine: {i_pray}")
                time.sleep(i_pray["cooldown"])

            stack_before = s.size()

            # add exits from next_room to stack and que
            for direction in next_room["exits"]:
                # check if the direction is the return direction
                oposite_directions = {"n": "s", "s": "n", "e": "w", "w": "e"}
                if oposite_directions[direction] != current_room_dir:
                    n_dict = {str(next_room["room_id"]): direction}

                    if str(n_dict) not in local_visited:
                        s.push(n_dict)

            # update stack on db
            db.update_stack(player, s.get_stack())

            stack_after = s.size()

            # if we dont push any rooms to the stack, we hit dead end => start BFT
            if stack_before == stack_after:

                # BFT will return shortest PATH to the next non-visited room
                shortest_path = []
                try:
                    # if current_room_id == s.stack[-1].id (you hit a dead end in looped nodes(cyclic graph))
                    # take s.stack[-2].id as TARGET if it exist
                    # if it doesnt (means the stack is empty) you are finished
                    if next_room["room_id"] == list(s.stack[-1].keys())[0]:
                        # BFS entry and target nodes:
                        # both have to be instances of room objects
                        # get rooms from DB by their ID
                        start = db.get_room_by_id(next_room["room_id"])
                        target = db.get_room_by_id(
                            list(s.stack[-2].keys())[0])
                        print(f'>>>> HIT A LOOPED NODE <<<<')
                        shortest_path = traverse(
                            start, target, db)

                    else:
                        # BFS entry and target nodes:
                        # get room from DB by its ID
                        start = db.get_room_by_id(next_room["room_id"])
                        target = db.get_room_by_id(
                            list(s.stack[-1].keys())[0])

                        shortest_path = traverse(
                            start, target, db)

                    traverse_path(shortest_path, player, db, db_id)

                except IndexError:
                    print('We are done!')

        else:
            print(
                f"{current_room} already visited")
예제 #12
0
    return None, None


def move_player(move):
    player.travel(move.dir)
    traversalPath.append(move.dir)
    prevRoom = move.origin
    currRoom = player.currentRoom.id
    # if loop handle assiging exits
    if currRoom in visited.keys() and visited[prevRoom][move.dir] == '?':
        visited[currRoom][move.reverse()] = prevRoom
        visited[prevRoom][move.dir] = currRoom


while stack.size() > 0:
    move = stack.pop()
    move.dir and move_player(move)
    prevRoom = move.origin
    currRoom = player.currentRoom.id

    # new room found
    if currRoom not in visited.keys():
        visited[currRoom] = {}
        visited[currRoom]['?'] = 0
        exits = player.currentRoom.getExits()

        for exit in exits:
            if exit not in visited[currRoom]:
                # If played moved and exit is where we entered the room from
                if move.dir and exit == move.reverse():
예제 #13
0
class DbSession(object):
    """Provides an API for users to make changes to an in-memory database with transactions.

    Attributes:
        database: An instance of an in-memory database.
        transaction_stack: A stack of active transactions.
        current_trans: The currently active transaction. Transactions are a set of keys which
            represent keys in the database that have been edited during the current transaction.
    """
    def __init__(self):
        self.database = InMemoryDatabase()
        self.transaction_stack = Stack()
        self.current_trans = None
        self.reset_transaction_state()
    
    def reset_transaction_state(self):
        self.current_trans = set() if self.transaction_stack.is_empty() else self.transaction_stack.current()
        # Transaction stack should always have a 'base' transaction which can't be rolled back/commited
        self.transaction_stack = Stack(self.current_trans)
        
    def pop_transaction(self):
        self.transaction_stack.pop()
        self.current_trans = self.transaction_stack.current()

    def has_open_transaction(self):
        return self.transaction_stack.size() > 1
        
    def begin(self):
        self.current_trans = set()
        self.transaction_stack.push(self.current_trans)
        
    def rollback(self):
        if not self.has_open_transaction():
            print('NO TRANSACTION')
        else:
            map(self.database.remove, list(self.current_trans))
            self.pop_transaction()
        
    def commit(self):
        if not self.has_open_transaction():
            print('NO TRANSACTION')
        else:
            self.database.flatten()
            self.reset_transaction_state()

    def set_var(self, var, value):
        if var in self.current_trans:
            self.database.change(var, value)
        else:
            self.database.add(var, value)
            self.current_trans.add(var)
    
    def unset_var(self, var):
        self.set_var(var, None)
            
    def get_var(self, var):
        print(self.database.get(var) or 'NULL')
    
    def num_equal_to(self, value):
        print(self.database.num_equal_to(value))

    def __repr__(self):
        return '{}\nTransaction Stack: {}'.format(self.database, self.transaction_stack)