Пример #1
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
Пример #2
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
Пример #3
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)
Пример #4
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
Пример #6
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
Пример #7
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
Пример #8
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
Пример #9
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
Пример #10
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
Пример #11
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():
        if maze[row][column] == 'T':
            return True
        else:
            # Try NORTH
            if row != 0 and not maze[row - 1][column] in ('*', '.'):
                stack.push((row - 1, column))
                maze[row-1][column] = '.'
            # Try SOUTH
            elif row != maze.getHeight() and not maze[row + 1][column] in('*','.'):
                stack.push((row + 1, column))
                maze[row+1][column] = '.'
            # Try EAST
            elif column != maze.getWidth() and not maze[row][column + 1] in('*','.'):
                stack.push((row,column + 1))
                maze[row][column + 1] = '.'
            # Try WEST
            elif column != 0 and not maze[row][column - 1] in ('*','.'):
                stack.push((row,column - 1))
                maze[row][column - 1] = '.'
            
    return False
Пример #12
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
Пример #13
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
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
Пример #16
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
Пример #17
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
def queue_to_stack(queue):
    """Converts queue to a stack"""
    output_stack = ArrayStack()
    start_queue = copy.deepcopy(queue)
    temporary_stack = ArrayStack()

    while start_queue.isEmpty() is False:
        elem = start_queue.pop()
        temporary_stack.push(elem)

    while temporary_stack.isEmpty() is False:
        elem = temporary_stack.pop()
        output_stack.push(elem)

    return output_stack
Пример #19
0
def queue_to_stack(queue):
    """
    Converts queue to stack.
    """
    temp_queue = ArrayQueue()
    temp_stack = ArrayStack()  #elements are in reversed order
    result_stack = ArrayStack()
    while not queue.isEmpty():
        elem = queue.pop()
        temp_queue.add(elem)
        temp_stack.push(elem)
    while not temp_queue.isEmpty():
        queue.add(temp_queue.pop())
    while not temp_stack.isEmpty():
        result_stack.push(temp_stack.pop())  #we reverse elements
    return result_stack
Пример #20
0
def solveMaze(row, column, maze):
    # 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] == FINISH:
            return True
        if maze[row][column] == VISITED:
            continue

        # Cell has not been visited.
        # Mark it as visited.
        maze[row][column] = VISITED

        # Push adjacent unvisited positions onto the stack:
        # Part 3:
        for row, column in [(row - 1, column), (row + 1, column),
                            (row, column - 1), (row, column + 1)]:
            if maze[row][column] != BARRIER or VISITED:
                stack.push((row, column))
    return False
Пример #21
0
# Part 8:
# Get and print the value at the top of stack2 without removing it:
# <your code>

item = stack2.peek()

print("The value at the top of stack2:", item)
printStack2()

# Part 9:
# Use isEmpty() to check whether stack1 and stack2 are empty.
# If either is empty, print a message saying it is empty.
# If either is not empty, print a message saying it is not empty.
# <your code>

if stack1.isEmpty() or stack2.isEmpty():
    print("stack1 is empty")
else:
    print("stack2 is not empty")

print()

# Part 10:
# Add the odd single-digit numbers to stack1 with 9 at the top:
# <your code>

for i in range(9, 0, -2):
    stack1.push(i)

print("After adding the odd single-digit numbers to stack1:")
print2Stacks()
Пример #22
0
 def arclear_unit_test(self):
     temp = ArrayStack()
     for count in range(4):
           temp.push(count+1)
     temp.clear()
     self.assertEqual(temp.isEmpty(), True)
Пример #23
0
class PFEvaluator(object):
    
    def __init__(self, scanner):
        self._expressionSoFar = ""
        self._operandStack = ArrayStack()
        self._scanner = scanner
        
    def evaluate(self):
        while self._scanner.hasNext():
            currentToken = Token(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,int(t1.getValue()),
                        int(t2.getValue())))
                self._operandStack.push(result)
            else:
                print(currentToken.getValue(),currentToken.getType())
                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 AttributeError("Unknow operator")
        return result