String 计算作为字符串输入的方程式

String 计算作为字符串输入的方程式,string,math,python-3.x,equation,String,Math,Python 3.x,Equation,我必须写多个函数来解一道数学难题。其中一个函数接受方程的一侧并计算答案。方程式以字符串形式输入。我创建变量是为了继续计算数字,这样22就是22,而不是2,2等等。当这个函数运行时,它会打印-4。参数Blackout设置为22-11*4。我很困惑问题是什么,以及我得到-4的原因。也许这个等式是在倒读,跳过一些数字 def compute(Blackout): numberBuild = "" operator = "" prev = 0 total = 0 for i in range (0 ,

我必须写多个函数来解一道数学难题。其中一个函数接受方程的一侧并计算答案。方程式以字符串形式输入。我创建变量是为了继续计算数字,这样22就是22,而不是2,2等等。当这个函数运行时,它会打印-4。参数Blackout设置为22-11*4。我很困惑问题是什么,以及我得到-4的原因。也许这个等式是在倒读,跳过一些数字

def compute(Blackout):
numberBuild = ""
operator = ""
prev = 0
total = 0
for i in range (0 , len(Blackout)):
    current = Blackout[i]

    if current.isdigit():
        numberBuild = current
    else:
        operator = current

    if prev == 0 and operator != "":
        prev = numberBuild
        numberBuild = ""

    if prev != 0 and operator != "":
        if operator == "+":
            total = total + int(prev)
        elif operator == "-":
            total = total - int(prev)
        elif operator == "x":
            total = total * int(prev)
        elif operator == "/":
            total = total / int(prev)
    prev = 0
    i + 1

print(total)

天哪,你们班的一半同学今天一定问过这个问题……是的,我们已经跳过了我们一直在做的事情。问题不是我不理解这个概念,而是我在实际执行它时遇到了问题。代码中有x,字符串中有*2。您如何处理运营优先级?所以,*,/在+,之前执行-大多数人使用树结构,我会使用,函数。。。3.你试过调试吗?断点/跟踪4。这里已经有一些关于数学表达式求值的问题。。。