Python在函数中传递不起作用

时间:2016-05-31 09:56:15

标签: python-3.x

我正在python中执行一个程序,它接受一个中缀并将其转换为后缀(波兰表示法),然后对其进行评估。当我将一个字符串传递给函数infixToPostfix时,问题就来了(如果我传递一个像“2 + 3 * 5”这样的字符串它运行完美,但如果我传递一个字符串变量它会爆炸)

class StackClass:

    def __init__(self, itemlist=[]):
        self.items = itemlist

    def isEmpty(self):
        if self.items == []:
            return True
        else:
            return False

    def peek(self):
        return self.items[-1:][0]

    def pop(self):
        return self.items.pop()

    def push(self, item):
        self.items.append(item)
    return 0

def parse_rpn(expression):
    stack = []

    for val in expression.split(' '):
        if val in ['-', '+', '*', '/', '^']:
            op1 = stack.pop()
            op2 = stack.pop()
            if val == '-': result = op2 - op1
            if val == '+': result = op2 + op1
            if val == '*': result = op2 * op1
            if val == '/': result = op2 / op1
            if val == '^': result = op2** op1
            stack.append(result)
        else:
            stack.append(float(val))

    return stack.pop()

def infixToPostfix(infixexpr):
    prec = {}
    prec['^'] = 3
    prec['*'] = 2
    prec['/'] = 2
    prec['+'] = 1
    prec['-'] = 1
    opStack = StackClass()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        else:
            while (not opStack.isEmpty()) and \
                (prec[opStack.peek()] >= prec[token]):
                    postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)

if __name__ == '__main__':
    with open('data.in', 'r') as infile:
        data = infile.read().replace('\n', '')
    print(data)
    b = infixToPostfix( data )

输入文件:

"2 + 3 * 5"

1 个答案:

答案 0 :(得分:0)

您的输入文件包含不必要的引号。从文件中删除它们,或处理代码中的引号。从文件中读取已经给你一个字符串。