Exemple #1
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
Exemple #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
Exemple #3
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
Exemple #4
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)
Exemple #5
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)
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
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
Exemple #9
0
 def arpeek_unit_test(self):
 temp = ArrayStack()
 for count in range(5):
       temp.push(count+1)
 self.assertEqual(temp.peek(), 5)
Exemple #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.
    # Cell has not been visited, so mark it and push adjacent unvisited
    #     positions onto the stack
    position_stack = ArrayStack()
    current_position = (row, column)
    position_stack.push(current_position)

    while len(position_stack) != 0:
        if maze[current_position[0]][current_position[1]] == "T":
            print(maze[current_position[0]][current_position[1]])
            return True
        else:
            north = (current_position[0] - 1, current_position[1])
            east = (current_position[0], current_position[1] + 1)
            south = (current_position[0] + 1, current_position[1])
            west = (current_position[0], current_position[1] - 1)

            try:
                if maze[north[0]][north[1]] == "T":
                    position_stack.push(north)
                    current_position = north
                    continue
                elif maze[north[0]][north[1]] == " ":
                    maze[north[0]][north[1]] = "-"
                    position_stack.push(north)
                    current_position = north
                    continue
            except:
                pass
            try:
                if maze[east[0]][east[1]] == "T":
                    position_stack.push(east)
                    current_position = east
                    continue
                elif maze[east[0]][east[1]] == " ":
                    maze[east[0]][east[1]] = "-"
                    position_stack.push(east)
                    current_position = east
                    continue
            except:
                pass
            try:
                if maze[south[0]][south[1]] == "T":
                    position_stack.push(south)
                    current_position = south
                    continue
                elif maze[south[0]][south[1]] == " ":
                    maze[south[0]][south[1]] = "-"
                    position_stack.push(south)
                    current_position = south
                    continue
            except:
                pass
            try:
                if maze[west[0]][west[1]] == "T":
                    position_stack.push(west)
                    current_position = west
                    continue
                if maze[west[0]][west[1]] == " ":
                    maze[west[0]][west[1]] = "-"
                    position_stack.push(west)
                    current_position = west
                    continue
            except:
                pass

            position_stack.pop()
            current_position = position_stack.peek()
            continue

    return False
Exemple #11
0
sRow = ArrayStack()
sCol = ArrayStack()
svalue = ArrayStack()

lastRow = enterPointRow
lastCol = enterPointCol

sRow.push(enterPointRow)
sCol.push(enterPointCol)
svalue.push(2)

sRow.push(enterPointRow)
sCol.push(enterPointCol + 1)
svalue.push(2)

while sRow.peek() != exitPointRow or sCol.peek() != exitPointCol:
    #for i in range(19):
    row = sRow.peek()
    col = sCol.peek()
    crosssite = 0
    #print(g1[row][col-1])
    #print(g1[row+1][col])
    #print(g1[row][col+1])
    #print(g1[row-1][col])
    if g1[row][col - 1] == ' ':
        if row != lastRow or (col - 1) != lastCol:
            sRow.push(row)
            sCol.push(col - 1)
            crosssite += 1
    if g1[row + 1][col] == ' ':
        if (row + 1) != lastRow or col != lastCol:
Exemple #12
0
from arraystack import ArrayStack

a = ArrayStack()

a.push('+')
a.push('*')

a.peek()
a.peek()
Exemple #13
0
for i in range(0, len(stack1)):
    try:
        x = stack1.pop()
        stack2.push(x)
    except KeyError:
        pass

print("After moving evens back to stack2 (in original order):")
print2Stacks()

# 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")