Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中缀到后缀(计算器)_Python - Fatal编程技术网

python中缀到后缀(计算器)

python中缀到后缀(计算器),python,Python,我有一个家庭作业要做计算器(中缀到后缀) 运行此代码时出现语法错误(如果expr*,则语法无效):*如何修复此错误代码 顺便说一句,我是一名新程序员,这个问题对于专家来说可能很简单。如果您能尽快给出答案,我将非常高兴 class Op: def __init__(self, num_in, num_out, fn): """ A postfix operator num_in: int num_out: int fn: ac

我有一个家庭作业要做计算器(中缀到后缀) 运行此代码时出现语法错误(如果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)
}

看一看。如果你尝试像

raw_input("Enter a postfix expression (or nothing to quit): ")
在您的主要功能中,它应该工作得更好

干杯,
Peter

谢谢您的帮助,但我在Python 3.2中运行了这段代码,如果我没有弄错的话,Python 2.x中正在使用原始输入。但是我再次遇到类似的错误。(如果expr:)您的输入是什么样子的?为什么要在输入调用中执行此eval调用?input(eval('\n输入后缀表达式(或不退出):')).strip像这样。为什么在输入中使用eval?它只是围绕提示,而不是围绕从用户读取的输入,对吗?不过,您可以发布发生错误的完整堆栈跟踪吗?
raw_input("Enter a postfix expression (or nothing to quit): ")