コード例 #1
0
def queue_to_stack(my_queue):
    q = deepcopy(my_queue)
    s = LinkedStack()
    while not q.isEmpty():
        s.add(q.peek())
        q.pop()
    return s
コード例 #2
0
 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))
コード例 #3
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
コード例 #4
0
    def test_push_to_stack(self):
        name = "Jose"

        node = Node(name)
        stack = LinkedStack()

        stack.push(node)

        self.assertEqual(len(stack), 1)
コード例 #5
0
ファイル: palindrom_ua.py プロジェクト: PavloBryliak/Lab13
 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
コード例 #6
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)
コード例 #7
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
コード例 #8
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)
コード例 #9
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)
コード例 #10
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)
コード例 #11
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)
コード例 #12
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
コード例 #13
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)
コード例 #14
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
コード例 #15
0
def topoSort(chart):
    stack = LinkedStack()
    chart.clearVertexMarks()
    for v in chart.vertices():
        if not v.isMarked():
            dfs(chart, v, stack)
    return stack
コード例 #16
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
コード例 #17
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()
コード例 #18
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()
コード例 #19
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)
コード例 #20
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
コード例 #21
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
コード例 #22
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
コード例 #23
0
 def predecessor(self, item):
     """
     Returns the largest item that is smaller 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()
             if biggest <= node.data <= item:
                 biggest = node.data
             if node.right != None:
                 stack.push(node.right)
             if node.left != None:
                 stack.push(node.left)
     return biggest if biggest != 0 else None
コード例 #24
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()
コード例 #25
0
    def rangeFind(self, low, high):
        '''
        Returns a list of the items in the tree, where low <= item <= high."""
        :param low:
        :param high:
        :return:
        '''

        lst = []

        if not self.isEmpty():
            stack = LinkedStack()
            stack.push(self._root)
            while not stack.isEmpty():
                node = stack.pop()
                if low <= node.data <= high:
                    lst.append(node.data)

                if node.right != None:
                    stack.push(node.right)
                if node.left != None:
                    stack.push(node.left)
        return lst
コード例 #26
0
ファイル: brackets.py プロジェクト: sorry666/Some_codes
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()
コード例 #27
0
ファイル: brackets.py プロジェクト: deepcapsule/Python
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()
コード例 #28
0
ファイル: brackets.py プロジェクト: hieugomeister/ASU
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
コード例 #29
0
ファイル: project2.py プロジェクト: mwleeds/cs260
def bracketsBalance(exp):
    #checks if the parentheses and brackets all match
    stk = LinkedStack()
    for l in exp: 
        if l in ['(','[']:
            stk.push(l) #push opening braces onto the stack
        elif l in [')',']']:
            if stk.isEmpty():
                return False #the list began with a closing bracket
            fromStack = stk.pop()
            if (l == '(' and fromStack != ')') or (l == '[' and fromStack != ']'):
                return False #non-matching symbols
    if stk.isEmpty(): return True #they all matched up
コード例 #30
0
class Evaluator(object):
    """Evaluator for postfix expressions.
    Assumes that the input is a syntactically correct
    sequence of tokens."""
   
    def __init__(self, scanner):
        """Sets the initial state of the evaluator."""
        self._operandStack = LinkedStack()
        self._scanner = scanner

    def evaluate(self):
        """Returns the value of the postfix expression."""
        for currentToken in self._scanner:
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            elif currentToken.isOperator(): 
                right = self._operandStack.pop()
                left = self._operandStack.pop()
                result = Token(self._computeValue(currentToken,
                                                  left.getValue(),
                                                  right.getValue()))
                self._operandStack.push(result)
        result = self._operandStack.pop()
        return result.getValue();   

    def _computeValue(self, op, value1, value2):
        """Utility routine to compute a value."""
        result = 0
        theType = op.getType()
        if theType == Token.PLUS:
            result = value1 + value2
        elif theType == Token.MINUS:
            result = value1 - value2
        elif theType == Token.MUL:
            result = value1 * value2
        elif theType == Token.REMDR:
            result = value1 % value2
        elif theType == Token.EXPO:
            result = value1 ** value2
        elif theType == Token.DIV:
            if value2 == 0:
                raise ZeroDivisionError("Attempt to divide by 0")
            else:
                result = value1 // value2
        return result
コード例 #31
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()
コード例 #32
0
ファイル: palindrome.py プロジェクト: Bdarmits/cs_ucu_lab13
    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
コード例 #33
0
class Evaluator(object):
    """Evaluator for postfix expressions.
    Assumes that the input is a syntactically correct
    sequence of tokens."""
    def __init__(self, scanner):
        """Sets the initial state of the evaluator."""
        self._operandStack = LinkedStack()
        self._scanner = scanner

    def evaluate(self):
        """Returns the value of the postfix expression."""
        for currentToken in self._scanner:
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            elif currentToken.isOperator():
                right = self._operandStack.pop()
                left = self._operandStack.pop()
                result = Token(
                    self._computeValue(currentToken, left.getValue(),
                                       right.getValue()))
                self._operandStack.push(result)
        result = self._operandStack.pop()
        return result.getValue()

    def _computeValue(self, op, value1, value2):
        """Utility routine to compute a value."""
        result = 0
        theType = op.getType()
        if theType == Token.PLUS:
            result = value1 + value2
        elif theType == Token.MINUS:
            result = value1 - value2
        elif theType == Token.MUL:
            result = value1 * value2
        elif theType == Token.REMDR:
            result = value1 % value2
        elif theType == Token.EXPO:
            result = value1**value2
        elif theType == Token.DIV:
            if value2 == 0:
                raise ZeroDivisionError("Attempt to divide by 0")
            else:
                result = value1 // value2
        return result
コード例 #34
0
ファイル: brackets.py プロジェクト: mwleeds/cs260
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
コード例 #35
0
"""
コード例 #36
0
class Translator(object):
    """Translates infix expressions to postfix expressions."""

    def __init__(self, scanner):
        """Sets the initial state of the translator."""
        self._expressionSoFar = ""
        self._operatorStack = LinkedStack()
        self._scanner = scanner


    def translate(self):
        """Returns a list of tokens that represent the postfix
        form of sourceStr.  Assumes that the infix expression
        in sourceStr is syntactically correct"""
        postfix = list()
        for currentToken in self._scanner:
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                postfix.append(currentToken)
            elif currentToken.getType() == Token.LPAR:
                self._operatorStack.push(currentToken)
            elif currentToken.getType() == Token.RPAR:
                topOperator = self._operatorStack.pop()
                while topOperator.getType() != Token.LPAR:
                    postfix.append(topOperator)
                    topOperator = self._operatorStack.pop()
            else:
                while not self._operatorStack.isEmpty() and \
                      self._operatorStack.peek().getPrecedence() >= \
                      currentToken.getPrecedence():
                    postfix.append(self._operatorStack.pop())
                self._operatorStack.push(currentToken)
        while not self._operatorStack.isEmpty():
            postfix.append(self._operatorStack.pop())
        return postfix
   
    def __str__(self):
        """Returns a string containing the contents of the expression
        processed and the stack to this point."""
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else: 
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operatorStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operators on the stack          : " + \
                      str(self._operatorStack)
        return result

    def translationStatus(self):
        return str(self)
コード例 #37
0
 def __init__(self, scanner):
     """Sets the initial state of the translator."""
     self._expressionSoFar = ""
     self._operatorStack = LinkedStack()
     self._scanner = scanner
コード例 #38
0
"""
コード例 #39
0
 def __init__(self, scanner):
     """Sets the initial state of the evaluator."""
     self._operandStack = LinkedStack()
     self._scanner = scanner