Exemple #1
0
def getOut(startRow, startCol, maze, showProcess=False):
   """Finds a way out of the maze, if it exists."""
   choices = LinkedStack()
   choices.push(findStartPos(maze))
   
   while not choices.isEmpty():
      c = choices.pop()
      if maze[c[1]][c[0]] == "G":
         return True
      else:
         maze[c[1]][c[0]] = "."
         
         if showProcess:
            print(maze)
            input()
         
         
         for newX, newY in [(c[0]+1, c[1]), (c[0]-1, c[1]),
                            (c[0], c[1]+1), (c[0], c[1]-1)]:
            
            if newX >= 0 and newX < maze.getWidth() and \
               newY >= 0 and newY < maze.getHeight() and \
               maze[newY][newX] not in ".*":
               choices.push((newX, newY))
      
   return False
Exemple #2
0
    def detectWin(self):
        """Returns True if all the disks are on the rightmost tower."""
        stack = LinkedStack()
        for x in range(self.size - 1, -1, -1):
            stack.push(Disk(x))

        return self.towers[2] == stack
Exemple #3
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."""
        # Stacks for operands
        self._operandStack = LinkedStack()
        
        # Scanner for scanning a string into tokens, OR a list of tokens
        self._scanner = scanner

    def evaluate(self):
        """Returns the value of the postfix expression."""
        # For each token in our scanner or list,
        # If it's an operand, push the token
        # If it's an operator pop off two tokens from the stack,
        #  compute the value, and then push the value back on the stack as a new Token
        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)
        
        # The result is the last thing left in the stack
        result = self._operandStack.pop()
        return result.getValue()   

    def _computeValue(self, op, value1, value2):
        """Utility routine to compute a value."""
        
        result = 0
        theType = op.getType()
        
        # Use python's application of an operator depending on theType of the token
        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")
            else:
                result = value1 // value2
        elif theType == Token.MODULO:
            result = value1 % value2

        elif theType == Token.EXPONENT:
            result = value1 ** value2
                
        return result
class Translator(object):
    """Translates infix expressions to postfix expressions."""
    def __init__(self, scanner):
        """Sets the initial state of the translator."""
        # Keeps track of the infix expression we've seen so far
        self._expressionSoFar = ""

        # Stack for operators
        self._operatorStack = LinkedStack()

        # Scanner to tokenize a string
        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"""
        # Use a python list to store the postfix tokens
        postfix = list()

        # For each token in our scanner
        for currentToken in self._scanner:
            # Keep track of what has been seen so far
            self._expressionSoFar += str(currentToken) + " "

            # If the token is an int, add to end of postfix list
            if currentToken.getType() == Token.INT:
                postfix.append(currentToken)

            # If the token is an (, push it on the stack
            elif currentToken.getType() == Token.LPAR:
                self._operatorStack.push(currentToken)

            # If the token is an ), pop from the stack until we see a (
            #  and add to end of postfix list
            elif currentToken.getType() == Token.RPAR:
                while not self._operatorStack.isEmpty(
                ) and self._operatorStack.peek().getType() != Token.LPAR:
                    postfix.append(self._operatorStack.pop())

                if not self._operatorStack.isEmpty():
                    self._operatorStack.pop()

            elif currentToken.getType() == Token.EXPONENT:

                while not self._operatorStack.isEmpty() \
                    and self._operatorStack.peek().getPrecedence() > currentToken.getPrecedence():
                    postfix.append(self._operatorStack.pop())
                self._operatorStack.push(currentToken)

            # Otherwise, the token is an operator.
            else:
                # While there are tokens on the stack that have higher precedence
                # than the current token, remove them from the stack and add to end of postfix
                while not self._operatorStack.isEmpty() \
                    and self._operatorStack.peek().getPrecedence() >= currentToken.getPrecedence():
                    postfix.append(self._operatorStack.pop())
            # Finally, push the current token onto the stack
                self._operatorStack.push(currentToken)

        # At the end, pop the remaining tokens from the stack and add to the end of postfix
        while not self._operatorStack.isEmpty():
            postfix.append(self._operatorStack.pop())

        # return our postfix expression
        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)