Ejemplo n.º 1
0
def topoSort(chart):
    stack = LinkedStack()
    chart.clearVertexMarks()
    for v in chart.vertices():
        if not v.isMarked():
            dfs(chart, v, stack)
    return stack
def queue_to_stack(my_queue):
    q = deepcopy(my_queue)
    s = LinkedStack()
    while not q.isEmpty():
        s.add(q.peek())
        q.pop()
    return s
    def convert(self):
        # cache the result
        if not self._pfTokens:
            # save the converted expression (tokens)
            self._pfTokens = []
            # stack to store operators and operands
            stack = LinkedStack()
            for token in self._scanner:
                # append the operand to list
                if not token.isOperator():
                    self._pfTokens.append(token)
                # Token.OPENPAREN & Token.CLOSEPAREN are operators,
                # so must be called before token.isOperator().
                elif token.getType() == Token.OPENPAREN:
                    stack.push(token)
                elif token.getType() == Token.CLOSEPAREN:
                    for i in range(len(stack)):
                        operator = stack.pop()
                        if operator.getType() == Token.OPENPAREN:
                            break
                        self._pfTokens.append(operator)
                elif token.isOperator():
                    # pop operators in the stack whose precedence is not smaller
                    for i in range(len(stack)):
                        if (stack.peek().getType() == Token.OPENPAREN
                                or stack.peek().getPrecedence() <
                                token.getPrecedence()):
                            break
                        self._pfTokens.append(stack.pop())
                    stack.push(token)

            for i in range(len(stack)):
                self._pfTokens.append(stack.pop())

        return self._pfTokens
Ejemplo n.º 4
0
def topo_sort(g, start_label=None):
    stack = LinkedStack()
    g.clear_vertex_marks()
    for v in g.vertices():
        if not v.is_marked():
            dfs(g, v, stack)
    return stack
Ejemplo n.º 5
0
def topoSort(g, startLabel=None):
    stack = LinkedStack()
    g.clearVertexMarks()
    for v in g.vertices():
        if not v.isMarked():
            dfs(g, v, stack)
    return stack
 def test_linkedstack_pop_returnselement(self):
     stack = LinkedStack()
     for i in range(10):
         stack.push(i + 1)
     for i in range(10):
         val = stack.pop()
         assert_equal(10 - i, val)
         assert_equal(10 - i - 1, len(stack))
Ejemplo n.º 7
0
    def test_push_to_stack(self):
        name = "Jose"

        node = Node(name)
        stack = LinkedStack()

        stack.push(node)

        self.assertEqual(len(stack), 1)
Ejemplo n.º 8
0
 def _is_palindrom(word):
     ls = LinkedStack()
     for i in range(len(word) // 2):
         ls.add(word[i])
     md = len(word) // 2 if len(word) % 2 == 0 else len(word) // 2 + 1
     for i in range(md, len(word)):
         if ls.pop() != word[i]:
             return False
     return True
Ejemplo n.º 9
0
 def _is_palindrom(word):
     ls = LinkedStack()
     for i, c in enumerate(word):
         if i < len(word) // 2:
             ls.push(c)
         elif i >= (len(word) - 1) // 2 + 1:
             if c != ls.pop():
                 return False
     return True
Ejemplo n.º 10
0
 def is_palindrome(word):
     stack = LinkedStack()
     for index in range(len(word) // 2):
         stack.push(word[index])
     for index in range((len(word) + 1) // 2, len(word)):
         if stack.peek() == word[index]:
             stack.pop()
         else:
             return False
     return True
Ejemplo n.º 11
0
 def node_preorder(self):
     if not self.isEmpty():
         stack = LinkedStack()
         stack.push(self._root)
         while not stack.isEmpty():
             node = stack.pop()
             yield node
             if node.right != None:
                 stack.push(node.right)
             if node.left != None:
                 stack.push(node.left)
Ejemplo n.º 12
0
def traverseFromVertex(graph, startVertex, process, collection=LinkedStack()):
    chart.clearVertexMarks()
    collection.add(startVertex)
    while not collection.isEmpty():
        v = collection.pop()
        if not v.isMarked():
            v.setMark()
            process(v)
            for vertex in v.neighboringVertices():
                if not vertex.isMarked():
                    collection.add(vertex)
Ejemplo n.º 13
0
 def preorder(self):
     """Supports a preorder traversal on a view of self."""
     if not self.isEmpty():
         treeStack = LinkedStack()
         treeStack.push(self._root)
         while not treeStack.isEmpty():
             node = treeStack.pop()
             yield node.data
             if node.right != None:
                 treeStack.push(node.right)
             if node.left != None:
                 treeStack.push(node.left)
Ejemplo n.º 14
0
def brackets_Checker():
    stk = LinkedStack()
    for ch in exp:
        if ch in ['[', '(']:
            stk.push(ch)
        elif ch in [']', ')']:
            if stk.isEmpty():
                return False
            chFromStack = stk.pop()
            if ch == ']' and chFromStack != '[' or ch == ')' and chFromStack != '(':
                return False
        return stk.isEmpty()
Ejemplo n.º 15
0
def queue_to_stack(queue):
    """Return a stack that contains items from the queue."""
    stack = LinkedStack()
    item_list = []

    for item in queue:
        item_list.insert(0, item)

    for item in item_list:
        stack.push(item)

    return stack
Ejemplo n.º 16
0
 def __iter__(self):
     """Supports a preorder traversal on a view of self."""
     if not self.isEmpty():
         stack = LinkedStack()
         stack.push(self._root)
         while not stack.isEmpty():
             node = stack.pop()
             yield node.data
             if node.right is not None:
                 stack.push(node.right)
             if node.left is not None:
                 stack.push(node.left)
Ejemplo n.º 17
0
    def successor(self, item):
        """
        Returns the smallest item that is larger than
        item, or None if there is no such item.
        :param item:
        :type item:
        :return:
        :rtype:
        """
        biggest = 0
        if not self.isEmpty():
            stack = LinkedStack()
            stack.push(self._root)
            while not stack.isEmpty():

                node = stack.pop()
                # print(smallest, node.data)
                if node.data >= biggest:
                    biggest = node.data
                if node.right != None:
                    stack.push(node.right)
                if node.left != None:
                    stack.push(node.left)
        smallest = biggest
        # print(smallest)
        if not self.isEmpty():
            stack = LinkedStack()
            stack.push(self._root)
            while not stack.isEmpty():

                node = stack.pop()
                # print(smallest, node.data)
                if item <= node.data <= smallest:
                    smallest = node.data
                if node.right != None:
                    stack.push(node.right)
                if node.left != None:
                    stack.push(node.left)
        # print(smallest)
        return smallest if smallest != 0 else None
Ejemplo n.º 18
0
    def test_pop_from_stack(self):
        name = "Jose"

        node = Node(name)
        stack = LinkedStack()

        stack.push(node)

        self.assertEqual(len(stack), 1)

        popped = stack.pop()

        self.assertEqual(popped, node)
        self.assertEqual(len(stack), 0)
Ejemplo n.º 19
0
def bracketsBalance(exp):
    """exp is s string that represents the expression"""
    stk = LinkedStack()
    for ch in exp:
        if ch in ["[", "("]:
            stk.push(ch)
        elif ch in [']', ')']:
            if stk.isEmpty():
                return False
            chFromStck = stk.pop()
            if ch == ']' and chFromStck != '[' or \
            ch == ')' and chFromStck != '(' :
                return False
    return stk.isEmpty()
Ejemplo n.º 20
0
def bracketsBalance(exp):
    """exp is  a string that represents the expression """
    stk = LinkedStack()
    for ch in exp:
        if ch in ['[', '(']:
            stk.push(ch)
        elif ch in [']', ')']:
            if stk.isEmpty():
                return False
            chFromStack = stk.pop()
            # Brackets must be of same type and match up
            if ch == ']' and chFromStack != '[' or ch == ')' and chFromStack != '(':
                return False
    return stk.isEmpty()
Ejemplo n.º 21
0
 def operate(self):
     '''Operate the postfix expression.'''
     stack = LinkedStack()
     for operand in self._tokens:
         if operand not in PostfixExpression._operator:
             # push the operand to the stack
             stack.push(operand)
         else:
             # operate two operand on the top of stack with the operation
             opRight = float(stack.pop())
             opLeft = float(stack.pop())
             res = PostfixExpression._operator[operand](opLeft, opRight)
             # push the result onto the stack
             stack.push(res)
     return stack.pop()
Ejemplo n.º 22
0
def bracketsBalance(exp):
    """exp represents the expression"""
    stk = LinkedStack()  # Create a new stack
    for ch in exp:  # Scan across the expression
        if ch in ['[', '(']:  # Push an opening bracket
            stk.push(ch)
        elif ch in [']', ')']:  # Process a closing bracket
            if stk.isEmpty():  # Not balanced
                return False
            chFromStack = stk.pop()
            # Brackets must be of same type and match up
            if ch == ']' and chFromStack != '[' or \
               ch == ')' and chFromStack != '(':
                return False
    return stk.isEmpty()  # They all matched up
Ejemplo n.º 23
0
    def levelorder(self):
        """Supports a levelorder traversal on a view of self."""
        if not self.isEmpty():
            stack = LinkedStack()
            stack.push(self.root)

            yield self.root.data
            while not stack.isEmpty():
                node = stack.pop()

                if node.left != None:
                    yield node.left.data
                    stack.push(node.right)
                if node.right != None:
                    yield node.right.data
                    stack.push(node.left)
Ejemplo n.º 24
0
def mazeSolver(maze, start, to_text=False, data_structure='stack'):
    """takes a maze and its starting point (as a tuple of row, column) and solves the maze. Maze walls must be *
    characters and the ending point must be a "T" character. Free spaces must be an empty space, " ". """
    # read the grid and set up stack
    grid = maze_reader(maze)
    print("maze without attempts:\n", grid)
    if data_structure == 'stack':
        _queue = LinkedStack()
    else:
        _queue = LinkedQueue(
        )  #TODO implement a linkedQueue structure with push
    _queue.push(start)
    # track choices:
    choice_count = 0
    #use stack data structure to explore maze and find a path to the end.
    while not _queue.isEmpty():
        _pop = _queue.pop()
        # print("popping ",_pop)
        if grid[_pop[0]][_pop[1]] == 'T':
            choice_count += 1
            print("Finished maze: \n")
            print(grid)
            if to_text:
                maze_text(grid, "solution.txt")
            return choice_count
        else:
            # if the _pop location did not return the character "T", leave a breadcrumb to not revisit.
            if grid[_pop[0]][_pop[1]] != 'O' and grid[_pop[0]][
                    _pop[1]] != 'T' and grid[_pop[0]][_pop[1]] != 'P':
                choice_count += 1
                grid[_pop[0]][_pop[1]] = 'O'
            # print("grid row, column is ",_pop[0],_pop[1],"\n")
            # print(grid)
            left = grid[_pop[0]][(_pop[1] - 1)]
            right = grid[_pop[0]][(_pop[1] + 1)]
            down = grid[(_pop[0] - 1)][_pop[1]]
            up = grid[(_pop[0] + 1)][_pop[1]]
            if left == ' ' or left == 'T':
                _queue.push((_pop[0], (_pop[1] - 1)))
            if right == ' ' or right == 'T':
                _queue.push((_pop[0], (_pop[1] + 1)))
            if up == ' ' or up == 'T':
                _queue.push(((_pop[0] + 1), _pop[1]))
            if down == ' ' or down == 'T':
                _queue.push(((_pop[0] - 1), _pop[1]))
    #if stack becomes empty, there is no path.
    return choice_count
Ejemplo n.º 25
0
def isPalindrome(word: str) -> bool:
    '''
    True if a word read from left equal to from right else False.
    '''
    wordLen = len(word)
    if wordLen == 1 or wordLen == 0:
        return True

    stack = LinkedStack()
    middle = wordLen // 2
    for index in range(0, middle):
        stack.push(word[index])

    for index in range(wordLen - middle, wordLen):
        if word[index] != stack.pop():
            return False
    return True
Ejemplo n.º 26
0
    def height(self):
        hgt = LinkedStack()

        def recurse(node, count):
            if node != None:
                if count > hgt.peek():
                    hgt.push(hgt.pop() + 1)
                recurse(node.left, count + 1)
                recurse(node.right, count + 1)

        if self.isEmpty():
            return None
        else:
            hgt.push(-1)
            recurse(self.root, 0)

        return hgt.pop()
Ejemplo n.º 27
0
    def is_palindrome(word: str) -> bool:
        """Check whether the word is a palindrome."""
        stack = LinkedStack()

        for index, char in enumerate(word, 1):
            if char.isalpha() and index <= len(word) / 2:
                stack.push(char)

            elif char.isalpha() and (index > len(word) / 2) \
                    and (index != (len(word) / 2) + 0.5):
                if stack.isEmpty():
                    return False

                char_from_stack = stack.pop()
                if char != char_from_stack:
                    return False

        return stack.isEmpty()
Ejemplo n.º 28
0
    def is_palindrome(self, word):
        # check if word is palindrome
        half_1, half_2 = word[:len(word) // 2], word[len(word) // 2:]

        # cut first letter, whcih is not important
        if len(half_2) != len(half_1):
            half_2 = half_2[1:]

        stack = LinkedStack()
        for let in half_1:
            stack.push(let)

        for i in range(len(half_2)):
            if half_2[i] != stack.peek():
                return 0
            stack.pop()

        return 1
Ejemplo n.º 29
0
    def predecessor(self, item):
        pred = LinkedStack()

        def recurse(node, item):
            if node != None:
                if item <= node.data:
                    recurse(node.left, item)
                elif item > node.data:
                    pred.push(node.data)
                    recurse(node.right, item)

        if self.isEmpty():
            return None
        else:
            recurse(self.root, item)

        result = None
        if not pred.isEmpty():
            result = pred.pop()

        return result
Ejemplo n.º 30
0
    def successor(self, item):  #FIXME: Incomplete
        succ = LinkedStack()

        def recurse(node, item):
            if node != None:
                if item >= node.data:
                    recurse(node.right, item)
                elif item < node.data:
                    succ.push(node.data)
                    recurse(node.left, item)

        if self.isEmpty():
            return None
        else:
            recurse(self.root, item)

        result = None
        if not succ.isEmpty():
            result = succ.pop()

        return result