簡體   English   中英

用遞歸解決完全帶括號的表達式

[英]solving fully parenthesized expressions with recursion

我無法想出一個可以解決完全帶括號的方程的遞歸方法,例如((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)

你的語法是:

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)

嘗試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

解析有效數據的輸入,然后使用compiler模塊解析表達式,如下所示:

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

然后你可以使用:

eval(expr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM