예제 #1
0
def evaluate(express):
    ops = Stack()
    vals = Stack()
    for s in express.split():
        if s in "+,-,*,/,sqrt".split(','):
            ops.push(s)
        elif s == '(':
            pass
        elif s == ')':
            op = ops.pop()
            v = vals.pop()
            if op == '+':
                v += vals.pop()
            elif op == '-':
                v -= vals.pop()
            elif op == '*':
                v *= vals.pop()
            elif op == '/':
                v /= vals.pop()
            elif op == 'sqrt':
                v = v**0.5
            vals.push(v)
        else:
            vals.push(float(s))
    return vals.pop()
예제 #2
0
파일: chap_03.py 프로젝트: embatbr/ctci
    def version_2(test):
        (given, expected) = test

        original_stack = Stack()
        sorted_stack = Stack()

        for g in given:
            original_stack.push(g)

        # starts here

        num_eltos = original_stack.size

        for i in range(num_eltos):
            pivot = original_stack.pop()

            num_swaps = 0
            while (not sorted_stack.is_empty()) and (pivot < sorted_stack.peek()):
                original_stack.push(sorted_stack.pop())
                num_swaps += 1
            sorted_stack.push(pivot)

            for _ in range(num_swaps):
                sorted_stack.push(original_stack.pop())

        # sorts in reverse order (smallest on top)
        while not sorted_stack.is_empty():
            original_stack.push(sorted_stack.pop())

        given_str = ''.join(original_stack.to_array()) # doesn't count in the O(.) calculation
        return given_str == expected
예제 #3
0
파일: chap_03.py 프로젝트: embatbr/ctci
        def push(self, value):
            if self.cur_stack_index < 0:
                self.stacks.append(Stack())
                self.cur_stack_index = 0

            cur_stack = self.stacks[self.cur_stack_index]

            if cur_stack.size == self.threshold:
                cur_stack = Stack()
                self.stacks.append(cur_stack)
                self.cur_stack_index += 1

            cur_stack.push(value)
예제 #4
0
파일: chap_03.py 프로젝트: embatbr/ctci
    def version_1(test):
        forward_stack = Stack()
        backward_stack = Stack()

        for t in test:
            forward_stack.push(t)

        while not forward_stack.is_empty():
            backward_stack.push(forward_stack.pop())

        result = ''.join(backward_stack.to_array())

        return test == result
예제 #5
0
파일: cal.py 프로젝트: xflywind/pycal
def parse_infix(expression: str) -> List[str]:
    stack: Stack[str] = Stack()
    result: List[str] = []
    for expr in tokenize(expression):
        if not is_float(expr) and expr not in symbols:
            raise SymbolError()

        if is_float(expr):
            result.append(expr)

        elif expr == ")":
            while stack.top != "(":
                result.append(stack.pop())
            stack.pop()

        elif expr == "(":
            stack.push(expr)

        elif stack.top and compare_priority(expr, stack.top):
            result.append(stack.pop())
            while stack.top and compare_priority(expr, stack.top):
                result.append(stack.pop())
            stack.push(expr)
        else:
            stack.push(expr)

    while stack:
        result.append(stack.pop())
    return result
예제 #6
0
def parse_object(tokens):
    s = Stack()
    tokens_count = len(tokens)
    n = 0
    while n < tokens_count:
        elem = tokens[n]
        n += 1
        if elem == ']':
            l = []
            while s.top() != '[':
                top = s.pop()
                l.insert(0, top)
            s.pop()
            s.push(l)
            continue

        if elem == '}':
            l = []
            while s.top() != '{':
                top = s.pop()
                l.insert(0, top)
            s.pop()
            if len(l) > 0 and not len(l) % 3 == 0 and not l.count(':') == len(l) / 3:
                raise ValueError
            d = {l[i]: l[i + 2] for i in range(0, len(l), 3)}
            s.push(d)
            continue

        s.push(elem)

    return s.top()
예제 #7
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
예제 #8
0
def depth_first_tree_search(problem):
    """Експандирај го прво најдлабокиот јазол во пребарувачкото дрво.

    :param problem:даден проблем
    :return: Node
    """
    return tree_search(problem, Stack())
예제 #9
0
def depth_first_graph_search(problem):
    """Експандирај го прво најдлабокиот јазол во пребарувачкиот граф.

    :param problem: даден проблем
    :return: Node
    """
    return graph_search(problem, Stack())
예제 #10
0
 def __init__(self):
     self.focus = Stack()
     self.running = False
     self.win = None
     self.s = None
     self.tabs = None
     self.bomb = None
예제 #11
0
 def flatten(self):
     """
     Sets each value list in the data to contain only the active value, effectively
     deleting the 'history' of each value list.
     """
     for var in self.data.keys():
         self.data[var] = Stack(self.data[var].current())
    def depth_first(self, xy1, xy2):
        """Execute a depth first search."""
        tile_col1, tile_row1 = self.the_map.xy_to_cr(xy1[0], xy1[1])
        tile_col2, tile_row2 = self.the_map.xy_to_cr(xy2[0], xy2[1])

        successor_to_parent_map = {}
        start_state = (tile_col1, tile_row1)
        successor_to_parent_map[(
            start_state,
            None)] = None  # (Successor, Action) -> (Parent, Action)

        open_list = Stack()
        open_list.push((start_state, None))
        closed = []

        while not open_list.isEmpty():
            current_state, action_to_current_state = open_list.pop()

            if current_state == (tile_col2, tile_row2):
                return self.__get_action_path(
                    (current_state, action_to_current_state),
                    successor_to_parent_map)

            if current_state not in closed:
                for successor_state, action, step_cost in self.__get_successors(
                        current_state):
                    open_list.push((successor_state, action))

                    if successor_state not in closed:
                        successor_to_parent_map[(successor_state, action)] = (
                            current_state, action_to_current_state)

            closed.append(current_state)
        return []
예제 #13
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)
예제 #14
0
def depth_first_tree_search(problem):
    """Search the deepest nodes in the search tree first."""
    # This search algorithm might not work in case of repeated paths.
    global frontier,counter
    if counter == -1:
        frontier=Stack()
    return tree_search(problem)
예제 #15
0
 def __init__(self, G):
     self.marked = [False for _ in range(G.V)]
     self.pre = Queue()  # push v to queue before recursion
     self.post = Queue()  # ... after recursion
     self.reverse_post = Stack()  # push v to stack after recursion
     for w in range(G.V):
         if not self.marked[w]:
             self.dfs(G, w)
예제 #16
0
 def path_to(self, v):
     if not self.has_path_to(v):
         return None
     edges = Stack()
     e = self.edgeTo[v]
     while e is not None:
         edges.push(e)
         e = self.edgeTo[e.From()]
     return edges
예제 #17
0
def traverse(world, traversal_path):

    # iterating through all rooms as unknown
    def is_unknown(graph):
        for k in graph:
            if '?' in graph[k].values():
                return True
        return False

    def find_new_move(visited, current_room):
        curr_room = current_room.id
        room_exits = visited[curr_room]
        for direction in room_exits:
            if room_exits[
                    direction] == '?' and current_room.get_room_in_direction(
                        direction).id not in visited:
                return direction
        return None

    def find_new_room(traversal_path, visited, curr_room, stack, reverse):

        while True:
            next_move = stack.pop()
            traversal_path.append(next_move)
            next_room = curr_room.get_room_in_direction(next_move)
            if '?' in visited[next_room.id].values():
                return next_room.id
            curr_room = next_room

    stack = Stack()
    curr = 0
    visited = {0: {}}
    curr_room = world.rooms[curr]
    reverse = {'n': 's', 'e': 'w', 's': 'n', 'w': 'e'}
    for direction in curr_room.get_exits():
        visited[curr_room.id][direction] = '?'
    while len(visited) < len(world.rooms) and is_unknown(visited):
        curr_room = world.rooms[curr]
        if curr_room not in visited:
            visited[curr_room.id] = {}
            for direction in curr_room.get_exits():
                visited[curr_room.id][direction] = '?'
        next_move = find_new_move(visited, curr_room)
        if not next_move:
            curr = find_new_room(traversal_path, visited, curr_room, stack,
                                 reverse)
        else:
            traversal_path.append(next_move)
            next_room = curr_room.get_room_in_direction(next_move)
            visited[curr][next_move] = next_room.id
            if next_room.id not in visited:
                visited[next_room.id] = {}
                for direction in next_room.get_exits():
                    visited[next_room.id][direction] = '?'
            visited[next_room.id][reverse[next_move]] = curr_room.id
            stack.push(reverse[next_move])
            curr = next_room.id
예제 #18
0
 def trace_cycle(self, v, w):
     stack = Stack()
     x = v
     while x != w:
         stack.push(x)
         x = self.edge_to[x]
     stack.push(w)
     stack.push(v)
     return stack
예제 #19
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]
예제 #20
0
 def path_to(self, v):
     if not self.has_path_to(v):
         return []
     path = Stack()
     x = v
     while x != self.s:
         path.push(x)
         x = self.edge_to[x]
     path.push(self.s)
     return path
예제 #21
0
    def analyze(self, word):
        word = Stack(*reversed(word))
        qi = self.q0
        stack = Stack(self.Z0)

        memory = [(qi, word, stack)]

        depth = 0
        new_memory = []

        for (qi, word, stack) in memory:
            possibleRules = list(
                filter(
                    lambda rule: rule[0] == qi and rule[1] in
                    (word.top(), 'ε') and rule[2] in
                    (stack[:len(rule[1])], 'ε'), self.ô))

            print(qi, word.reverse(), stack.reverse())
            print(possibleRules)
예제 #22
0
    def dfs_recursive(self, starting_vertex: T,
                      destination_vertex: T) -> PathType:
        """
        Return a list containing a path from
        starting_vertex to destination_vertex in
        depth-first order.

        This should be done using recursion.
        """
        # would hold the found path to destination_vertex
        correct_path = []
        # holds the visited vertices
        visited = set()
        # initialize the stack class
        stack = Stack()
        # push the starting_vertex as a list
        stack.push([starting_vertex])

        # the inner recursive function
        def inner_dfs_recursive(starting_vertex, destination_vertex):
            # pops off a path from the stack
            path = stack.pop()
            # picks the last vertex from the path
            current_vert = path[-1]

            # base case of current_vert is the destination_vertex
            if current_vert == destination_vertex:
                # assess the nonlocal correct_path
                nonlocal correct_path
                # point correct_path to the path
                correct_path = path
                # return from the recursive function
                return

            # for neighbors of current_vert
            for vertex in self.vertices[current_vert]:
                # if vertex has not been visited
                if vertex not in visited:
                    # add it to visited visited
                    visited.add(vertex)
                    # create a copy of path
                    new_path = list(path)
                    # append the vert to the new path
                    new_path.append(vertex)
                    # push the new path onto the stack
                    stack.push(new_path)

                    # recursively call inner_dfs_recursive with vertex as the starting_vertex
                    inner_dfs_recursive(vertex, destination_vertex)

        # call the recursive function
        inner_dfs_recursive(starting_vertex, destination_vertex)

        # return the path
        return correct_path
예제 #23
0
def playing(player):

    traversal_path = []

    visited_dict = {}
    visited_set = set()
    path = Stack()

    oposite_directions = {"s": "n", "n": "s", "e": "w", "w": "e"}

    while len(visited_set) < len(room_graph):
        current = player.current_room
        visited_set.add(current)
        # path.push(current.id)
        # traversal_path.append(current)

        # if current.id not in visited_set:
        # print(current.id)
        # visited_set.add(current.id)
        visited_dict[current.id] = {}

        # if len(current.get_exits()) == 1:
        #     direction = current.get_exits()
        #     path.pop()
        #     previous_room = path.stack[-1]
        #     visited_dict[current.id][direction] = previous_room
        #     player.travel(previous_room)

        unvisited = Queue()
        for direction in current.get_exits():
            if current.get_room_in_direction(direction) not in visited_set:
                # visited_dict[current.id][direction] = False
                # unvisited.enqueue(direction)
                unvisited.enqueue(direction)

        if unvisited.size() > 0:
            # direction = unvisited.dequeue()
            direction = unvisited.dequeue()
            path.push(direction)
            traversal_path.append(direction)
            player.travel(direction)
            
        else:
            # for direction in visited_dict[current.id]:
            #     if visited_dict[current.id][direction] == False:
            #         visited_dict[current.id][direction] = player.current_room.get_room_in_direction(direction)
            #         player.travel(direction)
            previous_room = path.pop()
            traversal_path.append(oposite_directions[previous_room])
            player.travel(oposite_directions[previous_room])
            
            

    return traversal_path
예제 #24
0
 def evaluate(self, vars):
     stack = Stack()
     queue = Queue()
     for elem in self._rpn:
         factory = OperatorFactory()
         operator = factory.newOperator(elem, stack, vars)
         if self.verbose == True:
             print elem, operator.evaluate()
         stack.push(operator.evaluate())
         if self.verbose == True:
             print stack.s()
     return stack.popAll()
예제 #25
0
def sort_stack(stack):

    s1 = stack
    s2 = Stack(s1.size)

    while(s1.is_empty() != True):
        temp = s1.pop()
        while(s2.is_empty() != True and s2.peek() > temp):
            s1.push(s2.pop())
        s2.push(temp)

    return s2
예제 #26
0
def sort_stack(stack):
    buf = Stack()
    while not stack.is_empty():
        cur = stack.pop()
        cnt = 0
        while not buf.is_empty() and cur < buf.peek():
            stack.push(buf.pop())
            cnt += 1
        buf.push(cur)
        for i in xrange(cnt):
            buf.push(stack.pop())
    while not buf.is_empty():
        stack.push(buf.pop())
예제 #27
0
def dfs(initial, _next, _test):
    s: Stack = Stack()
    marked = {initial}
    s.push(initial)
    while s:
        parent = s.pop()
        if _test(parent):
            return parent
        children = _next(parent)
        for child in children:
            if child not in marked:
                marked.add(child)
                s.push(child)
예제 #28
0
파일: cal.py 프로젝트: xflywind/pycal
def parse_sufix(expression: List[str]) -> float:
    stack: Stack[str] = Stack()
    result: float = 0.0
    for expr in expression:
        if is_float(expr):
            stack.push(expr)
        else:
            elem1: str = stack.pop()
            elem2: str = stack.pop()
            result = evaluate(expr, float(elem2), float(elem1))
            stack.push(str(result))
    if stack:
        result = float(stack.pop())
    return result
예제 #29
0
    def init_state(self):
        self.modules = [None, None, None, None, None, None, None, None]
        self.tabs = Tabs(5, 0, *["Empty"] * 8)
        self.focus = Stack()
        self.slot = -1

        bomb = self.bomb = Bomb(self)
        bomb.notify_on_finish(self.bomb_info_finished)
        self.update_bomb_info(bomb)

        chooser = ModuleChooser(self)
        self.focus.push(chooser)

        self.focus.push(bomb)
예제 #30
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