python中缀到Postfix(计算器)

时间:2014-04-12 06:57:29

标签: python

我有一个制作计算器的作业(中缀到后缀) 运行此代码时出现语法错误(语法无效如果expr * :*如何修复此错误代码?

顺便说一下,我是一名新的程序员,对于专家来说这个问题可能很简单。如果你能尽快给出答案,我将非常高兴。

class Op:
def __init__(self, num_in, num_out, fn):
    """
    A postfix operator

    num_in:     int
    num_out:    int
    fn:         accept num_in positional arguments,
                perform operation,
                return list containing num_out values
    """
    assert num_in  >= 0, "Operator cannot have negative number of arguments"
    self.num_in = num_in
    assert num_out >= 0, "Operator cannot return negative number of results"
    self.num_out = num_out
    self.fn = fn

def __call__(self, stack):
    """
    Run operator against stack (in-place)
    """
    args = stack.pop_n(self.num_in)         # pop num_in arguments
    res = self.fn(*args)                    # pass to function, get results
    stack.push_n(self.num_out, res)         # push num_out values back
ops = {
'*':  Op(2, 1, lambda a,b: [a*b]),          # multiplication
'/':  Op(2, 1, lambda a,b: [a//b]),         # integer division
'+':  Op(2, 1, lambda a,b: [a+b]),          # addition
'-':  Op(2, 1, lambda a,b: [a-b]),          # subtraction
'/%': Op(2, 2, lambda a,b: [a//b, a%b])     # divmod (example of 2-output op)

}

def postfix_eval(tokens):
"""
Evaluate a series of tokens as a postfix expression;
return the resulting stack
"""
if is_str(tokens):
    # if tokens is a string, treat it as a space-separated list of tokens
    tokens = tokens.split()

stack = Stack()
for token in tokens:
    try:
        # Convert to int and push on stack
        stack.append(int(token))
    except ValueError:
        try:
            # Not an int - must be an operator
            # Get the appropriate operator and run it against the stack
            op = ops[token]
            op(stack)         # runs Op.__call__(op, stack)
        except KeyError:
            # Not a valid operator either
            raise ValueError("unknown operator {}".format(token))
return stack

def main():
while True:
    expr = input(eval('\nEnter a postfix expression (or nothing to quit): ').strip()
    if expr:
        try:
            print("  => {}".format(postfix_eval(expr)))
        except ValueError as error:
            print("Your expression caused an error: {}".format(error))
    else:
        break

if __name__=="__main__":
main()

1 个答案:

答案 0 :(得分:0)

看看http://www.daniweb.com/software-development/python/threads/12326/how-to-do-input-in-python。如果你尝试像

那样的话
raw_input("Enter a postfix expression (or nothing to quit): ")

在你的主要功能中,它应该更好。

欢呼声, 彼得