首页 > 试题广场 >

表达式求值

[编程题]表达式求值
  • 热度指数:120380 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个字符串描述的算术表达式,计算出结果值。

输入字符串长度不超过 100 ,合法的字符包括 +, -, *, /, (, )0-9

数据范围:运算过程中和最终结果均满足 ,即只进行整型运算,确保输入的表达式合法

输入描述:

输入算术表达式



输出描述:

计算出结果值

示例1

输入

400+5

输出

405
print(int(eval(input())))
编辑于 2024-04-18 20:03:37 回复(0)
import sys
s=input()
def compute(lst):#计算无括号列表的值如:['1','+','2','*','-3','/','2','-','4'],
    s=[]
    for i in lst:#先计算乘除法
        if s and (i.isnumeric()&nbs***bsp;(i[0]=='-' and len(i)>1)) and s[-1] in ['*','/']:#如果i为正数或负数字符串且上一个符号为乘号或除号
            if s[-1]=='*':
                s[-2:]=[str(int(s[-2])*int(i))]
            if s[-1]=='/':
                s[-2:]=[str(int(s[-2])//int(i))]
        else:
            s.append(i)
    s1=[]
    for i in s:#计算加减法
        if s1 and s1 and (i.isnumeric()&nbs***bsp;(i[0]=='-' and len(i)>1)):
            if s1[-1]=='+':
                s1[-2:]=[str(int(s1[-2])+int(i))]
            if s1[-1]=='-':
                s1[-2:]=[str(int(s1[-2])-int(i))]
        else:
            s1.append(i)
    return int(s1[0])
def f(s):
    #为便于计算,在-前加0
    if s[0]=='-':
        s=('0'+s)
    while '(-' in s:
        s=s.replace('(-','(0-')
    lst=[]
    for c in s:
        if lst:
            if lst[-1].isnumeric() and c!=')':
                if c.isnumeric():
                    lst[-1]+=c
                else:
                    lst.append(c)
            else:
                if c==')':
                    i=len(lst)-1
                    while lst[i]!='(':#计算上一个左括号的位置
                        i-=1
                    temp=lst[i+1:]
                    lst[i:]=[str(compute(temp))]#计算括号内的值并添加到列表末尾
                else:
                    lst.append(c)                      
        else:
            lst.append(c)    
    #print('lst:',lst)
    return compute(lst)
print(f(s))

发表于 2024-03-07 19:16:18 回复(0)
print(eval(input()))


发表于 2023-11-06 14:56:31 回复(0)
fomula = input()
print(eval(fomula))

发表于 2023-09-18 13:41:36 回复(0)
#考虑了有负数的情况
s = input()
prior = {"(": 0, "+": 1, "-": 1, "/": 2, "*": 2, ")": 3}
s = list(s.strip(" "))
num_stack = []
op_stack = []


def tow_num():
    if len(num_stack) > 0:
        num2, num1 = num_stack.pop(), num_stack.pop()
        op = op_stack.pop()
        if op == "+":
            num_stack.append((num1 + num2))
        if op == "-":
            num_stack.append((num1 - num2))
        if op == "*":
            num_stack.append((num1 * num2))
        if op == "/":
            num_stack.append((num1 // num2))


i = 0
while i < len(s):
    c = s[i]
    if c.isdigit():
        num = 0
        pos = 0
        if (
            i != 0
            and s[i - 1] == "-"
            and s[i - 2] == "("
           &nbs***bsp;(i == 1 and s[i - 1] == "-")
        ):
            pos = 1
        else:
            pos = 0
        j = i
        while j < len(s) and s[j].isdigit():
            num = num * 10 + int(s[j])
            j += 1
        if pos == 1:
            num_stack.append(-num)
            op_stack.pop()
        else:
            num_stack.append(num)
        i = j
    elif c in "+-/*":
        while op_stack and prior[op_stack[-1]] >= prior[c]:
            tow_num()
        op_stack.append(c)
        i += 1
    elif c == "(":
        op_stack.append(c)
        i += 1
    elif c == ")":
        while op_stack[-1] != "(":
            tow_num()
        op_stack.pop()
        i += 1
while op_stack:
    tow_num()
print(num_stack[-1])

发表于 2023-05-05 19:19:39 回复(0)
import re


n = input().strip()
if len(n) in range(1, 101):
    a = len(re.findall(r"[^\+\-\*\/\(\,\)\d]", n))
    if a > 0:
        print("wrong")
    else:
        print(eval(n))

发表于 2023-04-09 16:54:05 回复(0)
s=input()
print(eval(s))
发表于 2023-02-14 09:13:27 回复(0)
print(eval(input()))

发表于 2023-02-03 21:12:04 回复(1)
def calc(s):
    args = list()
    temp = ''
    pn = 0
    pn_st = 0
    for i in range(len(s)):
        if s[i] == '(':
            pn += 1
            if pn == 1:
                pn_st = i + 1
        elif s[i] == ')':
            pn -= 1
            if pn == 0:
                args.append(calc(s[pn_st:i]))
        elif pn == 0:  # 没有括号的情况
            if s[i].isdigit():
                temp += s[i]
                if i == len(s) - 1:
                    args.append(int(temp))
                    temp = ''
                elif not s[i + 1].isdigit():
                    args.append(int(temp))
                    temp = ''
            else:
                args.append(s[i])

    ans1 = list()
    op = ''
    for i in range(len(args)):
        if isinstance(args[i], int):
            if op == '':
                ans1.append(args[i])
            elif op == '*':
                ans1[-1] = ans1[-1] * args[i]
                op = ''
            elif op == '/':
                ans1[-1] = ans1[-1] / args[i]
                op = ''
        elif args[i] == '*':
            op = args[i]
        elif args[i] == '/':
            op = args[i]
        elif args[i] == '+':
            ans1.append(args[i])
        elif args[i] == '-':
            ans1.append(args[i])

    ans = 0
    op = ''
    for i in range(len(ans1)):
        if isinstance(ans1[i], int):
            if op == '':
                ans = ans1[i]
            elif op == '+':
                ans += ans1[i]
            elif op == '-':
                ans -= ans1[i]
        elif ans1[i] == '+': 
            op = ans1[i]
        elif ans1[i] == '-':
            op = ans1[i]

    return ans


line = input()
print(calc(line))

发表于 2022-10-22 14:07:28 回复(0)
print(eval(input()))

发表于 2022-07-24 11:21:54 回复(0)
用最笨的最容易理解的方法
n = input()
n = str(n)
if n.count("+")>0:
    a = n.split("+")
    print(int(a[1])+int(a[0]))
elif n.count("-")>0:
    a = n.split("-")
    print(int(a[1])-int(a[0]))
elif n.count("*")>0:
    a = n.split("*")
    print(int(a[1])*int(a[0]))
elif n.count("/")>0:
    a = n.split("/")
    if int(a[1]) == 0:
        print("除数不能为0")
    else:
        print(int(a[1])/int(a[0]))
else:
    print("请按照要求输入")

发表于 2022-04-12 22:36:48 回复(4)
将传统表达式转换为逆波兰表达式进行求解。
#逆波兰表达式转换
equation = input()
if equation[0] == '-':
    equation = '0'+ equation
s1, s2 = [], []
temp_num = 0
#将中缀表达式转换为后缀表达式
for i in range(len(equation)):
    if equation[i].isdigit():
        temp_num = temp_num * 10 + int(equation[i])
        if i==len(equation)-1&nbs***bsp;not equation[i+1].isdigit():
            s2.append(temp_num)
            temp_num = 0
    elif equation[i] in ['+', '-', '*', '/']:
        if equation[i] == '-' and equation[i-1] in ['+', '-', '*', '/','(']:
            s2.append(0)
        while s1:
            if s1[-1] == '(':
                s1.append(equation[i])
                break
            elif equation[i] in ['*', '/'] and s1[-1] in ['+', '-']:
                s1.append(equation[i])
                break
            else:
                s2.append(s1.pop())
        if not s1:
            s1.append(equation[i])
    elif equation[i] == '(':
        s1.append(equation[i])
    else:
        while s1[-1] != '(':
            s2.append(s1.pop())
        s1.pop()
while s1:
    s2.append(s1.pop())
#计算后缀表达式
for i in range(len(s2)):
    if type(s2[i]) is not str:
        s1.append(s2[i])
    elif s2[i] == '+':
        a1 = s1.pop()
        a2 = s1.pop()
        temp = a2 + a1
        s1.append(temp)
    elif s2[i] == '-':
        a1 = s1.pop()
        a2 = s1.pop()
        temp = a2 - a1
        s1.append(temp)
    elif s2[i] == '*':
        a1 = s1.pop()
        a2 = s1.pop()
        temp = a2 * a1
        s1.append(temp)
    elif s2[i] == '/':
        a1 = s1.pop()
        a2 = s1.pop()
        temp = a2 / a1
        s1.append(temp)
print(s1[-1])

发表于 2021-10-30 23:49:58 回复(0)

问题信息

难度:
23条回答 38805浏览

热门推荐

通过挑战的用户

查看代码