Ejemplo n.º 1
0
 def arremstor_unit_test(self):
     temp = ArrayStack()
     for count in range(20):
           temp.push(count+1)
     for count in range(15):
           temp.pop()
     self.assertEqual(len(temp.items), 10)
 def test_arraystack_popallthrowsempty(self):
     stack = ArrayStack()
     for i in range(100):
         stack.push(i + 1)
     for i in range(100):
         stack.pop()
     stack.pop()
Ejemplo n.º 3
0
 def _is_palindrome(self, word):
     stack1 = ArrayStack(word)
     stack2 = ArrayStack(word[::-1])
     for i in range(len(word)):
         if stack1.pop() != stack2.pop():
             return False
     return True
Ejemplo n.º 4
0
class PFEvaluator(object):
    def __init__(self, scanner):
        self._expression_so_far = ""
        self._operand_stack = ArrayStack()
        self._scanner = scanner

    def evaluate(self):
        while self._scanner.has_next():
            current_token = self._scanner.next()
            self._expression_so_far += str(current_token) + " "
            if current_token.get_type() == Token.INT:  # 数字入栈
                self._operand_stack.push(current_token)
            elif current_token.is_operator():  # 操作符计算
                if len(self._operand_stack) < 2:  # 栈内数字小于2
                    raise AttributeError (\
                        "Too few operands on the stack")
                t2 = self._operand_stack.pop()
                t1 = self._operand_stack.pop()
                result = \
                        Token(self._compute_value(current_token,
                                                    t1.get_value(),
                                                    t2.get_value()))
                self._operand_stack.push(result)
            else:
                raise AttributeError("Unknown token type")
        if len(self._operand_stack) > 1:  # 计算完成后, 栈内深入数字大于2
            raise AttributeError(\
                "Too many operands on the stack")
        result = self._operand_stack.pop()
        return result.get_value()

    def __str__(self):
        result = "\n"
        if self._expression_so_far == "":
            result += \
                "Portion of expression processed none\n"
        else:
            result += "Portion of expression processed: " + \
                self._expression_so_far + "\n"
        if self._operand_stack.isEmpty():
            result += "Thre stack is empty"
        else:
            result += "Operands on the stack: " + \
                str(self._operand_stack)
        return result

    def _compute_value(self, op, value1, value2):
        result = 0
        the_type = op.get_type()
        if the_type == Token.PLUS:
            result = value1 + value2
        elif the_type == Token.MINUS:
            result = value1 - value2
        elif the_type == Token.MUL:
            result = value1 * value2
        elif the_type == Token.DIV:
            result = value1 // value2
        else:
            raise AttributeError("Unknown operator")
        return result
Ejemplo n.º 5
0
class PFEvaluator(object):
   
    def __init__(self, scanner):
        self._expressionSoFar = ""
        self._operandStack = ArrayStack()
        self._scanner = scanner

    def evaluate(self):
        while self._scanner.hasNext():
            currentToken = self._scanner.next()
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            elif currentToken.isOperator(): 
                if len(self._operandStack) < 2:
                    raise Exception("Too few operands on the stack")
                t2 = self._operandStack.pop()
                t1 = self._operandStack.pop()
                result = Token(self._computeValue(currentToken,
                                                  t1.getValue(),
                                                  t2.getValue()))
                self._operandStack.push(result)

            else:
                raise Exception("Unknown token type")
        if len(self._operandStack) > 1:
            raise Exception("Too many operands on the stack")
        result = self._operandStack.pop()
        return result.getValue();   

    def __str__(self):
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else: 
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operandStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operands on the stack          : " + \
                      str(self._operandStack)
        return result

    def _computeValue(self, op, value1, value2):
        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.DIV:
            result = value1 // value2;
        elif theType == Token.EXP:
            result = value1 ** value2;
        else:
            raise Exception("Unknown operator")
        return result
Ejemplo n.º 6
0
 def convert(self):
     operatorStack = ArrayStack() #this will hold operators and grouping symbols
     postfixExpression = "" #this will hold the final expression
     while self.scanner.hasNext():
         token_char = self.scanner.next()
         if token_char.getType() == 4: #it's an integer
             postfixExpression += str(token_char.getValue()) + " "
         elif token_char.getValue() in ['(','[']: #left parenthesis
             operatorStack.push(token_char)
         elif token_char.isOperator(): #it's an operator
             #pop off all the operators with equal or greater precedence
             while len(operatorStack) != 0 and operatorStack.peek().getPrecedence() >= token_char.getPrecedence():
                 postfixExpression += str(operatorStack.pop().getValue()) + " "
             #now we can push the new operator onto the stack
             operatorStack.push(token_char)
         elif token_char.getValue() in [')',']']: #right parenthesis
             while len(operatorStack) != 0 and operatorStack.peek().getValue() not in ['(','[']: #find the matching one
                 postfixExpression += str(operatorStack.pop().getValue()) + " "
             operatorStack.pop() #discard the left parenthesis
         elif token_char.getType() == 0 and token_char.getValue() not in ['(',')','[',']']: 
             raise Exception("Error: unknown character.") #unknown character
     #transfer over any remaining operators
     while len(operatorStack) != 0:
         postfixExpression += str(operatorStack.pop().getValue()) + " "
     return postfixExpression
Ejemplo n.º 7
0
 def convert(self):
     """Returns a list of tokens that represent the postfix
     form.  Assumes that the infix expression is syntactically correct"""
     postfix = []
     stack = ArrayStack()
     while self._scanner.hasNext():
         currentToken = self._scanner.next()
         if currentToken.getType() == Token.INT:
             postfix.append(currentToken)
         elif currentToken.getType() == Token.LPAR:
             stack.push(currentToken)
         elif currentToken.getType() == Token.RPAR:
             topOperator = stack.pop()
             while topOperator.getType() != Token.LPAR:
                 postfix.append(topOperator)
                 topOperator = stack.pop()
         else:
             while not stack.isEmpty() and \
                   currentToken.getType() != Token.EXPO and \
                   stack.peek().getPrecedence() >= currentToken.getPrecedence():
                 postfix.append(stack.pop())
             stack.push(currentToken)
     while not stack.isEmpty():
         postfix.append(stack.pop())
     return postfix
Ejemplo n.º 8
0
 def lipop_unit_test(self):
     temp = ArrayStack()
     for count in range(4):
           temp.push(count+1)
     temp.pop()
     self.assertEqual(temp.peek(), 3)
     temp.pop()
     self.assertEqual(len(temp),2)
Ejemplo n.º 9
0
class PFEvaluator(object):
   
    def __init__(self, scanner):
        self._expressionSoFar = ""
        self._operandStack = ArrayStack()
        self._scanner = scanner

    def evaluate(self):
        while self._scanner.hasNext():
            currentToken = self._scanner.next()
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            elif currentToken.isOperator(): 
                if len(self._operandStack) < 2:
                    raise AttributeError("Too few operands on the stack")
                t2 = self._operandStack.pop()
                t1 = self._operandStack.pop()
                result = Token(self._computeValue(currentToken,
                                                  t1.getValue(),
                                                  t2.getValue()))
                self._operandStack.push(result)

            else:
                raise AttributeError("Unknown token type")
        if len(self._operandStack) > 1:
            raise AttributeError("Too many operands on the stack")
        result = self._operandStack.pop()
        return result.getValue();   

    def __str__(self):
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else: 
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operandStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operands on the stack          : " + \
                      str(self._operandStack)
        return result

    def _computeValue(self, op, value1, value2):
        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.DIV:
            result = value1 // value2;
        else:
            raise Exception("Unknown operator")
        return result
Ejemplo n.º 10
0
class IFToPFConverter(object):

    def __init__(self, scanner):
        self._expressionSoFar = ""
        self._operatorStack = ArrayStack()
        self._scanner = scanner


    def convert(self):
        """Returns a list of tokens that represent the postfix
        form of sourceStr.  Assumes that the infix expression
        in sourceStr is syntactically correct"""
        postfix = []
        while self._scanner.hasNext():
            currentToken = self._scanner.next()
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.UNKNOWN:
                raise AttributeError("Unrecognized symbol")
            if currentToken.getType() == Token.INT:
                postfix.append(currentToken)
            elif currentToken.getType() == Token.LPAR:
                self._operatorStack.push(currentToken)
            elif currentToken.getType() == Token.RPAR:
                if self._operatorStack.isEmpty():
                    raise AttributeError("Too few operators")
                topOperator = self._operatorStack.pop()
                while topOperator.getType() != Token.LPAR:
                    postfix.append(topOperator)
                    if self._operatorStack.isEmpty():
                        raise AttributeError("Too few operators")
                    topOperator = self._operatorStack.pop()
            else:
                while not self._operatorStack.isEmpty() and \
                      currentToken.getType() != Token.EXPO 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):
        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 conversionStatus(self):
        return str(self)
Ejemplo n.º 11
0
class PFEvaluator(object):
   
    def __init__(self, postfix):
        self._expressionSoFar = ""
        self._operandStack = ArrayStack()
        self._postfix = postfix
        
    def evaluate(self):
        for currentToken in self._postfix:
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            else: 
                t2 = self._operandStack.pop()
                t1 = self._operandStack.pop()
                result = Token(self._computeValue(currentToken,
                                                  t1.getValue(),
                                                  t2.getValue()))
                self._operandStack.push(result)
        result = self._operandStack.pop()
        return result.getValue();   

    def __str__(self):
        result = "\n"
        if self._expressionSoFar == "":
            result += "Portion of expression processed: none\n"
        else: 
            result += "Portion of expression processed: " + \
                   self._expressionSoFar + "\n"
        if self._operandStack.isEmpty():
            result += "The stack is empty"
        else:
            result += "Operands on the stack          : " + \
                      str(self._operandStack)
        return result

    def _computeValue(self, op, value1, value2):
        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.DIV:
            if value2 == 0:
                raise ZeroDivisionError("Attempt to divide by 0")
            result = value1 // value2;
        elif theType == Token.EXPO:
            result = value1 ** value2;
        else:
            raise AttibuteError("Unknown operator")
        return result
Ejemplo n.º 12
0
def check_brackets(s):
    stack = ArrayStack()
    for i in s:
        if i == "(":
            stack.push("(")
        if i == ")":
            if stack.isEmpty():
                return False
            stack.pop()
    if stack.isEmpty():
        return True
    else:
        return False
def checkBalance(st):
    stck = ArrayStack()
    for i in st:
        if i == '[' or i == '{' or i == '(':
            stck.push(i)
        else:
            if i == ']' or i == '}' or i == ')':
                if stck.isEmpty() or stck.peek() != opposite(i):
                    return False
                else:
                    stck.pop()
    if stck.isEmpty():
        return True
    return False
Ejemplo n.º 14
0
 def find_palindromes(self, file, file_name):
     """
     method which finds palindroms.
     """
     words_list = self.read_file(file)
     stack = ArrayStack()
     result = []
     for word in words_list:
         word_len = len(word)
         if word_len == 1.0:
             result.append(word)
         else:
             word_mid = word_len // 2
             middle = word_len % 2
             for i in range(word_len):
                 if i < word_mid:
                     stack.push(word[i])
                 elif middle == 1 and i == word_mid:
                     continue
                 else:
                     if stack.pop() != word[i]:
                         check = False
                         break
                     check = True
             if check is True:
                 result.append(word)
     self.write_to_file(result, file_name)
     return result
Ejemplo n.º 15
0
    def find_palindromes(self, input_file, output_file):
        '''
        Find palindromes using stack
        '''
        palindroms = []

        self.input_file = input_file
        self.output_file = output_file

        words = self.read_file(self.input_file)

        for word in words:
            word_lst = list(word)
            word_stack = ArrayStack()

            flag = True

            for letter in range(len(word_lst)-1, -1, -1):
                word_stack.push(word[letter])

            while not word_stack.isEmpty():
                if word_stack.pop() != word_lst.pop():
                    flag = False
                    break

            if flag:
                palindroms.append("".join(word))

        self.write_to_file(self.output_file, palindroms)
        return palindroms
Ejemplo n.º 16
0
    def find_palindromes(self, read_from: str, write_to: str) -> list:
        """
        Finds all palindromes from the file and
        write it into another one
        Returns a list with palindromes
        """
        words = self.read_file(read_from)
        palindromes = list()
        stack_with_words = ArrayStack()
        reversed_word = ""

        for word in words:
            for char in word:
                stack_with_words.push(char)

            while not stack_with_words.isEmpty():
                reversed_word += stack_with_words.pop()

            if reversed_word == word:
                palindromes.append(word)

            reversed_word = ""

        self.write_in_file(write_to, palindromes)

        return palindromes
Ejemplo n.º 17
0
def is_matched_html(raw):
    """Return True if all HTML tags are properly matched;
    False Otherwise."""
    S = ArrayStack()
    # find first '<' character
    start = raw.find('<')
    while start != -1:
        # find next '>' character
        end = raw.find('>', start + 1)
        if end == -1:
            return False
        # strip away < >
        tag = raw[start + 1:end]
        # this is opening tag
        if not tag.startswith('/'):
            S.push(tag)
        # this is closing tag
        else:
            if S.is_empty():
                return False
            if tag[1:] != S.pop():
                return False
        start = raw.find('<', end + 1)
    # all tags matched
    return S.is_empty()
Ejemplo n.º 18
0
def getOut(row, column, maze):
    """(row,column) is the position of the start symbol in the maze.
    Returns True if the maze can be solved or False otherwise."""
    # States are tuples of coordinates of cells in the grid.
    stack = ArrayStack()
    stack.push((row, column))
    while not stack.isEmpty():
        (row, column) = stack.pop()
        if  maze[row][column] == 'T': 
            return True
        elif maze[row][column] != '.':
            # Cell has not been visited, so mark it and push adjacent unvisited
            # positions onto the stack
            maze[row][column] = '.'
            # Try NORTH
            if row != 0 and not maze[row - 1][column] in ('*', '.'):
                stack.push((row - 1, column))             
            # Try SOUTH
            if row + 1 != maze.getHeight() and not maze[row + 1][column] in ('*', '.'):         
                stack.push((row + 1, column))             
            # Try EAST
            if column + 1 != maze.getWidth() and not maze[row][column + 1] in ('*', '.'):         
                stack.push((row, column + 1))             
            # Try WEST
            if column != 0 and not maze[row][column - 1] in ('*', '.'):         
                stack.push((row, column - 1))
    return False
Ejemplo n.º 19
0
def test_stack():
    S = ArrayStack()
    S.push(5)
    print(S.top())
    S.push(6)
    print(len(S))
    print(S.pop())
    print(S.is_empty())
    print(S.data)
Ejemplo n.º 20
0
def isPalindrome(string):
    """Returns True if string is a palindrome
    or False otherwise."""
    stk = ArrayStack()
    for ch in string:
        stk.push(ch)
    for ch in string:
        if ch != stk.pop():
            return False
    return True
Ejemplo n.º 21
0
def stack_to_queue(stack):
    '''Convert stack to queue, without changing given stack
    peek of the stack is the first element in the queue'''
    queue = ArrayQueue()
    stack_copy = ArrayStack(stack)

    while len(stack_copy) != 0:
        queue.add(stack_copy.pop())

    return queue
def infixToPostfix(exp):
    stck = ArrayStack()
    postfix = ""
    for i in range(len(exp)):
        if isOperand(exp[i]):
            postfix += exp[i]
        else:
            if stck.isEmpty():
                stck.push(exp[i])
            else:
                if prec(exp[i]) >= prec(stck.peek()):
                    stck.push(exp[i])
                else:
                    while not stck.isEmpty() and prec(exp[i]) < prec(stck.peek()):
                        postfix += stck.pop()
                    stck.push(exp[i])
        # print "Stack:", stck.printStack(), "Expression:", postfix
    while not stck.isEmpty():
        postfix += stck.pop()
    return postfix
def infixToPostfix(exp):
    stck = ArrayStack()
    postfix = ""
    for i in range(len(exp)):
        if isOperand(exp[i]):
            postfix += exp[i]
        else:
            if stck.isEmpty():
                stck.push(exp[i])
            else:
                if prec(exp[i]) >= prec(stck.peek()):
                    stck.push(exp[i])
                else:
                    while not stck.isEmpty() and prec(exp[i]) < prec(stck.peek()):
                        postfix += stck.pop()
                    stck.push(exp[i])
        #print "Stack:", stck.printStack(), "Expression:", postfix
    while not stck.isEmpty():
        postfix += stck.pop()
    return postfix
Ejemplo n.º 24
0
 def check_palindrome(s):
     s = str(s)
     stack = ArrayStack()
     even = 1 if len(s) % 2 else 0
     half = len(s) // 2
     for i in range(half):
         stack.push(s[i])
     ind = half + even
     for i in range(half):
         if stack.pop() != s[ind + i]:
             return False
     return True
Ejemplo n.º 25
0
    def convert(self):
        postfix = [] #Creating an empty list to store the postfix expression
        storage = ArrayStack() #Creates a stack to store the operands when converting the expression.
        while self._infix.hasNext():
            current = self._infix.next()
            if current.getType() == Token.INT:
                postfix.append(current)
            elif current.getType() == Token.LeftPar:
                storage.push(current)
                self._operand += 1
            elif current.getType() == Token.RightPar:
                self._operator += 1
                topOpInSt = storage.pop()
                while topOpInSt.getType() != Token.LeftPar:
                    postfix.append(topOpInSt)
                    topOpInSt = storage.pop()
            elif current.getType() == Token.LeftBrac:
                storage.push(current)
                self._operand += 1
            elif current.getType() == Token.RightBrac:
                self._operator += 1
                a = storage.pop()
                while a.getType() != Token.LeftBrac:
                    postfix.append(a)
                    a = storage.pop()
            else:
		#The loop below tells the program to go through the array that is created so far, and as long as it is not empty and the precedence found in the Tokens.py file of the first item in the array is greater than or equal to the precedence of the current token the Scanner is on, the program continues.
                while not storage.isEmpty() and storage.peek().getPrecedence() >= current.getPrecedence():
                    postfix.append(storage.pop())
                storage.push(current)
        if self._operand > self._operator or self._operator > self._operator:
            return "Unbalanced Expression"
        while not storage.isEmpty():
            postfix.append(storage.pop())
        return postfix
def queue_to_stack(queue):
    '''
    Conver queue to stack.
    '''
    queue_copy = deepcopy(queue)
    stack = ArrayStack()
    while queue_copy:
        stack.push(queue_copy.pop())

    result = ArrayStack()
    while stack:
        result.push(stack.pop())
    return result
Ejemplo n.º 27
0
def stack_to_queue(stack):
    """
    Converts stack to queue.
    """
    temp_stack = ArrayStack()
    result_queue = ArrayQueue()
    while not stack.isEmpty():
        elem = stack.pop()
        result_queue.add(elem)
        temp_stack.push(elem)
    while not temp_stack.isEmpty():
        stack.push(temp_stack.pop())
    return result_queue
def stack_to_queue(stack):
    """
    Return queue from stack (front of queue is peek of stack).
    """
    copy_stack = ArrayStack()
    queue = ArrayQueue()
    for element in stack:
        copy_stack.push(element)

    while len(copy_stack) != 0:
        queue.add(copy_stack.pop())

    return queue
Ejemplo n.º 29
0
def queue_to_stack(queue):
    """
    Convert queue to stack
    """
    stack1 = ArrayStack()
    stack2 = ArrayStack()
    while len(queue) != 0:
        num = queue.pop()
        stack1.push(num)
    while len(stack1) != 0:
        num = stack1.pop()
        stack2.push(num)
    return stack2
def reverse_file(filename):
    """Overwrite a given file with contents line-by-line in reversed order"""
    S = ArrayStack()
    original = open(filename)

    for line in original:
        S.push(line.rstrip('\n'))  # we will re-insert newlines while writing
    original.close()

    # now write the contents in LIFO order
    output = open(filename, 'w')
    while not S.is_empty():
        output.write(S.pop() + '\n')  # add trailing new line
    output.close()
Ejemplo n.º 31
0
 def palindrome_search(line):
     """
     The function returns True if the word is a palindrome
     """
     s = ArrayStack()
     for letter in line:
         s.push(letter)
     reversed_line = ''
     while not s.isEmpty():
         reversed_line += s.pop()
     if line == reversed_line:
         return True
     else:
         return False
Ejemplo n.º 32
0
def is_match(expr):
    """Return True if all the delimiters are properly matched; False Otherwise;"""
    lefty = '({['
    righty = ')}]'
    stack = ArrayStack()
    for c in expression:
        if c in lefty:
            stack.push(c)
        elif c in righty:
            if stack.is_empty():
                return False
            if righty.index(c) != lefty.index(stack.pop()):
                return False
    return stack.is_empty()
def is_matched(expr):
    """Return True if  all delimiters properly match (or closed); False otherwise"""
    left_delimiters = "({["
    right_delimiter = ")}]"
    S = ArrayStack()
    for c in expr:
        if c in left_delimiters:
            S.push(c)
        elif c in right_delimiter:
            if S.is_empty():
                return False
            if right_delimiter.index(c) != left_delimiters.index(S.pop()):
                return False
    return S.is_empty()