4

我无法想出一种递归方法来解决完全带括号的方程......例如((3+2)/(1+4))。我能够想出一个递归解决方案来解决中缀表达式,比如+*+3421使用递归,但是对于像((3+2)/(1+4))我这样的东西有点卡住了。

def evalPrefix(exp):
    it = iter(exp)
    return evalPrefixInner(it)

def evalPrefixInner(it):
    item = it.next()
    if isInt(item):
        return int(item)
    else: 
        operand1 = evalPrefixInner(it)
        operand2 = evalPrefixInner(it)
        return execute(item, operand1, operand2)
4

3 回答 3

2

你的语法是:

expr ::= int | ( expr op expr )

正确的?

所以,忽略错误检查,比如......

def evalExpr(it):
    item = it.next()
    if isInt(item):
        return int(item)
    else: 
        //item should = lparen
        operand1 = evalExpr(it)
        op = it.next()        
        operand2 = evalExpr(it)
        rparen = it.next() 
        return execute(op, operand1, operand2)
于 2012-10-27T20:54:30.147 回答
2

尝试shunting-yard algorithm

dic={"+": lambda x, y:x+y,
     "-": lambda x, y:x-y,
     "/": lambda x, y:x/y,
     "%": lambda x, y:x%y,
     "*": lambda x, y:x*y}

def algo(x, op=None, nums=None):
    if x != "":
        op = op if op else []
        nums = nums if nums else []
        item = x[0]
        if item in ("+","-","%","/","*"):
            op.append(item)
        if item.isdigit():
            nums.append(item)
        if item==")":
            operator = op.pop()
            opd1, opd2 = int(nums.pop()), int(nums.pop())
            ans = dic[operator](opd1, opd2)
            nums.append(ans)
        return algo(x[1:], op, nums)
    else:
        if op and nums:
            operator = op.pop()
            opd1, opd2 = int(nums.pop()), int(nums.pop())
            return dic[operator](opd1, opd2)
        else:
            return nums[-1]

print algo("((3+2)/(1+4))")  #output :1
print algo("((5+2)*3*(2+5))") #output :147
于 2012-10-27T21:48:52.480 回答
0

解析有效数据的输入,然后使用compiler模块解析表达式,如下所示:

import compiler
expr = compiler.compile(r'((3+2)/(4+1))', 'err', 'eval')

然后你可以使用:

eval(expr)
于 2012-10-27T20:43:00.170 回答