1

I am trying to create a infix to postfix converter in python for a homework assignment, I found multiple ones online that seem simple enough but none of them meet the requirements I need. I have to use the following classes:

class Token(object):

    UNKNOWN     = 0             # unknown
    INT         = 4             # integer
    MINUS       = 5             # minus operator
    PLUS        = 6             # plus operator
    MUL         = 7             # multiply operator
    DIV         = 8             # divide operator

    FIRST_OP    = 5             # first operator code

    def getPrecedence(self):
        if self is '(':
            return 0

        elif self is '+'or '-':
            return 1

        elif self is '*' or '/':
            return 2

        else:
            return 3

    def _init_(self, value):
        if type(value) == int:
            self._type = Token.INT
        else:
        self._type = self._makeType(value)
        self._value = value

    def isOperator(self):
        return self._type >= Token.FIRST_OP

    def _str_(self):
        return str(self._value)

    def getType(self):
        return self._type

    def getValue(self):
        return self._value

    def _makeType(self, ch):
        if   ch == '*': return Token.MUL
        elif ch == '/': return Token.DIV
        elif ch == '+': return Token.PLUS
        elif ch == '-': return Token.MINUS
        else:           return Token.UNKNOWN;

I had to add the getPrecedence(): method, which returns an Integer that represents the precedence level of an operator. I also had to use the following class:

from token import Token

class Scanner(object):

    EOE = ';'        # end-of-expression
    TAB = '\t'       # tab

    def __init__(self, sourceStr):
        self._sourceStr = sourceStr
        self._getFirstToken()

    def hasNext(self):
        return self._currentToken != None

    def next(self):
        if not self.hasNext():
            raise Exception, "There are no more tokens"            
        temp = self._currentToken
        self._getNextToken()
        return temp

    def _getFirstToken(self):
        self._index = 0
        self._currentChar = self._sourceStr[0]
        self._getNextToken()

    def _getNextToken(self):
        self._skipWhiteSpace()
        if self._currentChar.isdigit():
            self._currentToken = Token(self._getInteger())
        elif self._currentChar == Scanner.EOE:
            self._currentToken = None
        else:
            self._currentToken = Token(self._currentChar)
            self._nextChar()

    def _nextChar(self):
        if self._index >= len(self._sourceStr) - 1:
            self._currentChar = Scanner.EOE
        else:
            self._index += 1
            self._currentChar = self._sourceStr[self._index]

    def _skipWhiteSpace(self):
        while self._currentChar in (' ', Scanner.TAB):
            self._nextChar()

    def _getInteger(self):
        num = 0
        while True:
            num = num * 10 + int(self._currentChar)
            self._nextChar()
            if not self._currentChar.isdigit():
                break
        return num

I have to write a program that converts a infix expression to a postfix expression. This program should use the Token and Scanner classes (which I have included above). The program should consist of a main function that preforms the inputs and outputs, and a class named IFToPFConverter. The main function receives a input string an creates a scanner with it. The scanner is then passed as a argument to the constructor of the converter object. The converter objects convert method is then run to convert the infix expression. This method returns a list of tokens that represent the postfix string. The main function then displays this string. Here is what I have so far:

from arrayStack import ArrayStack
from token import Token
from scanner import Scanner

class IFToPFConverter(object):

     def convert(self):
        opStack = Stack()
        postFixList = []

        while self._scanner.hasNext():
            currentToken = self._scanner.next()
            if currentToken in '0123456789'
                postFixList.append(currentToken)
            elif currentToken == '(':
                opStack.push(currentToken)
            elif currentToken == '*':
                opStack.push(currentToken)
            elif currentToken == '/':
                opStack.push(currentToken)
            elif currentToken == '+':
                opStack.push(currentToken)
            elif currentToken == '-':
                opStack.push(currentToken)
            elif currentToken == ')':
                opStack.push(currentToken)

         while not opStack.isEmpty():                
    
def main():
    sourceStr = raw_input("Please enter an expression:")
    scanner = Scanner(sourceStr)
    conversion = IFToConverter.convert(scanner)
    return conversion
    
main()  

I don't know where to go from here, I don't even know if what I am trying to do at in my IFToPFConverter class will work. I have seen much simpler infix to postfix converters.

4

0 回答 0