中缀表达式求值 Python C++

本文介绍了一种将中缀转后缀与后缀求值算法融合的新方法,直接对中缀表达式进行求值,适用于+-*/^运算。算法采用双栈结构,分别存放操作符和操作数,通过一次扫描完成计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过把“中缀转后缀”和“后缀求值”两个算法功能集成在一起(非简单的顺序调用),

实现对中缀表达式直接求值,新算法还是从左到右扫描中缀表达式,

但同时使用两个栈,一个暂存操作符,一个暂存操作数,来进行求值。

(支持 + - * / ^ 五种运算)

 

输入格式:

共1行,为1个字符串,即一个中缀表达式,

其中每个数字或符号间由一个空格隔开。

 

输出格式:

共1行,为一个整数,即求值的结果。

 

输入样例:

( 2 + 3 ) * 6 + 4 / 2

 

输出样例:

32

Python版

def domath(op,op1,op2):
    if op=='*':
        return op1*op2
    elif op=='/':
        return op1/op2
    elif op=='+':
        return op1+op2
    elif op=='-':
        return op1-op2
    else:
        return op1**op2
class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

def calculate(s):
    # 请在此编写你的代码(可删除pass语句)
    opStack=Stack()
    numStack=Stack()
    prec={}
    prec['^']=4
    prec['*']=3
    prec['/']=3
    prec['+']=2
    prec['-']=2
    prec['(']=1
    s=s.split()
    for token in s:            
        if token.isdigit():
            numStack.push(int(token))
        elif token=='(':
            opStack.push(token)
        elif token==')':
            toptoken=opStack.pop()
            while toptoken!='(':
                operand2=numStack.pop()
                operand1=numStack.pop()
                result=domath(toptoken,operand1,operand2)
                numStack.push(result)
                toptoken=opStack.pop()
        else:
            while(not opStack.isEmpty())and (prec[opStack.peek()]>=prec[token]):
                op=opStack.pop()
                operand2=numStack.pop()
                operand1=numStack.pop()
                result=domath(op,operand1,operand2)
                numStack.push(result)
            opStack.push(token)
    while not opStack.isEmpty():
        op=opStack.pop()
        operand2=numStack.pop()
        operand1=numStack.pop()
        result=domath(op,operand1,operand2)
        numStack.push(result)
    return numStack.pop()
print(int(calculate(input())))

C++版

#include <iostream>
#include<cstdio>
#include<algorithm>
#include <cstring>
#include<stack>
#include <string>
#include<math.h>
#define MAX 210
using namespace  std;


int domath(char op0,int op1,int op2)
{
    if(op0=='*')return op1*op2;
    else if(op0=='/')return op1/op2;
    else if (op0=='+')return op1+op2;
    else if(op0=='-')return op1-op2;
    else return pow(op1,op2);
}
int getpriority(char a)
{
    int priority;
    if(a=='^')priority=3;
    else if(a=='*'||a=='/')priority=2;
    else if(a=='+'||a=='-')priority=1;
    else if(a=='(')priority=0;
    
    return priority;
}
int main(int argc, char const *argv[])
{ 
    int operand2,operand1,result;
    string next;
    int a;
    getline(cin,next);
    int n=next.size();

    stack<int>nums;
    stack<char>op;

    for (int i = 0; i < n; ++i)
     {   
        if (next[i]==' ') continue;
        if(next[i]>='0'&&next[i]<='9')
             
            nums.push((next[i]-'0')*1);
       
        else if(next[i]=='(')
        {
            op.push(next[i]);
        }
        else if(next[i]==')')
        {
            char token=op.top();
            op.pop();
            while(token!='(')
            {
                operand2=nums.top();
                nums.pop();
                operand1=nums.top();
                nums.pop();
                result=domath(token,operand1,operand2);
                nums.push(result);
                token=op.top();
                op.pop();
            }
        }
        else
        {
            while(!op.empty()&&(op.top()!='(')&&(next[i]!=' ')&&(getpriority(op.top())>=getpriority(next[i])))
            {
                char opr=op.top();
                op.pop();
                operand2=nums.top();
                nums.pop();
                operand1=nums.top();
                nums.pop();
                result=domath(opr,operand1,operand2);
                nums.push(result);



            }
            if(next[i]!=' ')
            op.push(next[i]);
        }


        

    }
    while(!op.empty())
    {
        char opr=op.top();
        op.pop();
        operand2=nums.top();
        nums.pop();
        operand1=nums.top();
        nums.pop();
        result=domath(opr,operand1,operand2);
        nums.push(result);

    }


    int final=int(nums.top());
    printf("%d\n",final );
    return 0;
}

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值