簡體   English   中英

評估后綴表達式樹 - 計算器

[英]Evaluate Postfix Expression Tree - Calculator

我有從中綴生成后綴表達式並從后綴表示法生成表達式樹的代碼。 問題是,如果我給它一個像 45 / 15 * 3 這樣的表達式,它會給我結果 1 而不是 9,因為它首先解決了樹的最深層次。 我可以做另一種遍歷來正確評估表達式嗎?

def evaluate(self):

    if not self.is_empty():
        if not infix_to_postfix.is_operator(self._root):
            return float(self._root)
        else:
            A = self._left.evaluate()
            B = self._right.evaluate()
            if self._root == "+":
                return A + B
            elif self._root == "-":
                return A - B
            elif self._root == "*":
                return A * B
            elif self._root == "/":
                return A / B
def InfixToPostfix(exp: str):
    exp = exp.replace(" ", "")

    S = Stack()
    postfix = ""
    j = 0
    for i in range(len(exp)):
        if is_operand(exp[i]):
            if i + 1 <= len(exp) - 1 and is_operand(exp[i+1]):
                continue
            else:
                j = i
                while j - 1 >= 0 and is_operand(exp[j - 1]):
                    if is_operand(exp[j]):
                        j -= 1
                    else:
                        break
            postfix += exp[j:i + 1] + " "
        elif is_operator(exp[i]):
            while not S.is_empty() and S.top() != "(" and \ HasHigherPrecedence(S.top(), exp[i]):
                if is_operator(S.top()):
                    postfix += S.top() + " "
                else:
                    postfix += S.top()
                S.pop()
            S.push(exp[i])
        elif exp[i] == "(":
            S.push(exp[i])
        elif exp[i] == ")":
            while not S.is_empty() and S.top() != "(":
                if is_operator(S.top()):
                    postfix += S.top() + " "
                else:
                    postfix += S.top()
                S.pop()
        else:
            print("There's an invalid character")
            return

    while not S.is_empty():
        if S.top() == '(':
            S.pop()
            continue
        if is_operator(S.top()):
            postfix += S.top() + " "
        else:
            postfix += S.top()
        S.pop()

    return postfix


def HasHigherPrecedence(op1: str, op2: str):
    op1_weight = get_operator_weight(op1)
    op2_weight = get_operator_weight(op2)
    return op1_weight > op2_weight

您的示例 45 / 15 * 3 的后綴表達式將是:

45 15 / 3 *

所以生成的樹看起來像:

        * 
   /        3
45   15

所以你的遍歷算法看起來是正確的,因為它會做 45 / 15 = 3,然后 3 * 3 = 9。

在您的后綴生成器中,這個問題實際上非常小。 具體來說,在 function HasHigherPrecedence 中,您應該返回op1_weight >= op2_weight 它應該大於或等於,因為在諸如這個運算符具有相同優先級的示例中,它們應該按照它們出現的順序執行。 所以首先要進行划分。

暫無
暫無

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

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