首页 > 试题广场 >

四则运算

[编程题]四则运算
  • 热度指数:135105 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}对于输入的表达式,保证其形式合法、计算过程中全程合法、计算过程中不需要使用到实数、结果 {\rm ans} 满足 -10^3 \leqq {\rm ans} \leqq 10^3 。直接输出计算结果。

\hspace{15pt}保证表达式字符串由 0-9 的数字、加法 \texttt{`+'} 、减法 \texttt{`-'} 、乘法 \texttt{`*'} 、除法 \texttt{`/'} 、小括号 \texttt{`('},\texttt{`)'} 、中括号 \texttt{`['},\texttt{`]'} 、大括号 \texttt{`\{'},\texttt{`\}'} 组成,且运算符之间没有空格。

输入描述:
\hspace{15pt}输入一个长度为 1 \leqq {\rm len}(s) \leqq 10^3 、由题面所述符号构成的字符串,代表一个表达式。


输出描述:
\hspace{15pt}输出一个整数 \rm ans ,代表计算的答案。满足 -10^3 \leqq {\rm ans} \leqq 10^3
示例1

输入

3+2*{1+2*[-4/(8-6)+7]}

输出

25

说明

\hspace{15pt}在这个样例中,计算过程为:\begin{array}{ll}<br />& 3+2\times\big\{1+2\times{[-4 \div (8-6)+7]}\big\} \\<br />= & 3 + 2 \times \big\{1 + 2 \times [-4 \div {\color{orange}{\bf2}} + 7]\big\} \\<br />= & 3 + 2 \times \big\{1 + 2 \times [{\color{orange}{\bf{-2}}} + 7]\big\} \\<br />= & 3 + 2 \times \big\{1 + 2 \times {\color{orange}{\bf5}}\big\} \\<br />= & 3 + 2 \times \big\{1 + {\color{orange}{\bf10}}\big\} \\<br />= & 3 + 2 \times {\color{orange}{\bf11}} \\<br />= & 3 + {\color{orange}{\bf22}} \\<br />= & {\color{orange}{\bf25}}<br />\end{array}
def compare_op(op1: str, op2: str):
    if op1 in ['*', '/'] and op2 in ['*', '/']:
        return 0
    if op1 in ['+', '-'] and op2 in ['+', '-']:
        return 0
    if op1 in ['*', '/'] and op2 in ['+', '-']:
        return 1
    if op1 in ['(', '{', '[']:
        return -1
    return -1


def calc(num1, num2, op: str):
    if op == '+':
        return num1 + num2
    if op == '-':
        return num1 - num2
    if op == '*':
        return num1 * num2
    if op == '/':
        return num1 / num2
    raise ValueError


def is_match(left, right):
    case1 = left == '(' and right == ')'&nbs***bsp;left == '[' and right == ']'&nbs***bsp;left == '{' and right == '}'
    left, right = right, left
    case2 = left == '(' and right == ')'&nbs***bsp;left == '[' and right == ']'&nbs***bsp;left == '{' and right == '}'
    return case1&nbs***bsp;case2


while True:
    try:
        s = input()
        s_len = len(s)
        op_stack = []
        num_stack = []

        i = 0
        while i < s_len:
            ch = s[i]
            if ch.isnumeric():
                j = i
                # 如果是 i 位置是数字试图向后继续看以期获得完整的数字
                while j + 1 < s_len and s[j].isnumeric() and s[j + 1].isnumeric():
                    j += 1
                # 此时 [i, j + 1] 即为数字
                num_stack.append(int(s[i:j + 1]))
                i = j
            elif ch in ['(', '{', '[']:
                op_stack.append(ch)
            elif ch in [')', '}', ']']:
                # 一直计算, 直到碰到左半部分
                while True:
                    op = op_stack.pop()
                    if is_match(ch, op):
                        break
                    num2 = num_stack.pop()
                    num1 = num_stack.pop()
                    num_stack.append(calc(num1, num2, op))
            else:
                if i == 0 and ch == '-'&nbs***bsp;i >= 1 and s[i - 1] in ['(', '{', '[']:
                    num_stack.append(-1)
                    op_stack.append('*')
                else:
                    # 一直算, 直到op栈为空或者栈顶优先级小于当前
                    while len(op_stack) != 0 and compare_op(op_stack[-1], ch) >= 0:
                        num2 = num_stack.pop()
                        num1 = num_stack.pop()
                        op = op_stack.pop()
                        num_stack.append(calc(num1, num2, op))
                    op_stack.append(ch)
            i += 1

        while len(op_stack) > 0:
            num2 = num_stack.pop()
            num1 = num_stack.pop()
            op = op_stack.pop()
            num_stack.append(calc(num1, num2, op))

        final = num_stack.pop()
        if int(final) == final:
            final = int(final)
        print(final)
    except:
        break

发表于 2025-04-19 14:20:23 回复(0)
## 人生苦短,我用python
s = input().replace('{','(').replace('}',')').replace('[','(').replace(']',')')
print(eval(s))
发表于 2024-12-13 14:04:44 回复(0)
print(eval(input()))
抱歉python真的可以为所欲为哈哈哈哈

发表于 2023-01-26 10:55:52 回复(0)
s=input()
t=''
for i in s:
    if i in ['[','{']:
        t+='('
    elif i in [']','}']:
        t+=')'
    elif  i=='/':
        t+='//'
    else:
        t+=i
print(eval(t))

发表于 2022-10-24 00:40:43 回复(0)
s = list(input())
ss = []
dict_op = {')':'(', ']':'[', '}':'{'}
priority = {'+': 1, '-': 1, '*': 2, '/': 2}
i = 0
while i < len(s):
    if ord('0') <= ord(s[i]) <= ord('9'):
        j = i
        temp = ''
        while j < len(s) and ord('0') <= ord(s[j]) <= ord('9'):
            temp += s[j]
            j += 1
        ss.append(int(temp))
        i = j
    else:
        ss.append(s[i])
        i += 1
# 添加结束符
ss.append('#')
        
def process_stack(stack):
    # 操作数
    nums = []
    # 操作符
    ops = []
    # 判断负号和减号,当前一个字符为'('时当作数的一部分,不添加进操作符
    pre = '('
    neg_flag = 1
    for x in stack:
        if type(x) != str&nbs***bsp;ord('0') <= ord(x) <= ord('9'):
            nums.append(int(x) * neg_flag)
            neg_flag = 1
            pre = x
        else:
            if pre == '(':
                neg_flag = -1 if x == '-' else 1
            else:
                ops.append(x)
    # 只有一个操作符,直接返回
    if len(nums) == 1:
        return nums[0]
    while len(nums) > 1:
        if len(ops) == 1:
            # 这时操作符栈中只有一个操作符了,直接输出结果
            num2 = nums.pop(-1)
            num1 = nums.pop(-1)
            op = ops.pop(-1)
            return cal(num1, num2, op)
        elif priority[ops[-1]] >= priority[ops[-2]]:
            num2 = nums.pop(-1)
            num1 = nums.pop(-1)
            op = ops.pop(-1)
            # 如果遇到两个连续减号,需要变号
            if (op == '+'&nbs***bsp;op == '-') and ops[-1] == '-':
                num2 = num2 * -1
            nums.append(cal(num1, num2, op))
        else:
            # 先存栈顶,计算栈顶前一个数
            num_tmp = nums.pop(-1)
            op_tmp = ops.pop(-1)
            num2 = nums.pop(-1)
            num1 = nums.pop(-1)
            op = ops.pop(-1)
            # 还原栈顶
            nums.append(cal(num1, num2, op))
            nums.append(num_tmp)
            ops.append(op_tmp)
    return False


def cal(num1, num2, op):
    if op == '+':
        return num1 + num2
    elif op == '-':
        return num1 - num2
    elif op == '*':
        return num1 * num2
    else:
        return num1 / num2


res = 0
stack = [ss[0]]
i = 1
while len(stack) > 0:
    if ss[i] == '#':
        res = process_stack(stack)
        break    
    if ss[i] != ')' and ss[i] != ']' and ss[i] != '}':
        stack.append(ss[i])
        i += 1
        continue
    t = ss[i]
    # 获取左括号
    vers_op = dict_op[ss[i]]
    sub_stack = []
    while stack[-1] != vers_op:
        sub_stack = [stack.pop(-1)] + sub_stack
    # 弹出左括号
    stack.pop(-1)
    stack.append(process_stack(sub_stack))
    i += 1
print(res)
# print(process_stack("5-3+9*6*(6-10-2)"))
        
折腾了两个小时,艹
发表于 2022-09-04 05:12:14 回复(0)
print(eval(input()))
我这个答案是不是有点过分了😂😂
发表于 2022-08-26 17:26:01 回复(0)
# 分三种情况:
# 1、没有中括号和大括号,直接用eval函数求值
# 2、只有中括号没有大括号,先算中括号,再求值
# 3、既有中括号又有大括号,先算中括号,再算大括号,最后再求值
a = input()
if '[' not in a and ']' not in a and '{' not in a and '}' not in a:
    print(eval(a))
if '['  in a and ']'  in a and '{' not in a and '}' not in a:
    j = a.index('[')
    k = a.index(']')
    b = a.replace(a[j:k + 1], str(int(eval(a[j + 1:k]))))
    print(eval(b))
if '['  in a and ']'  in a and '{'  in a and '}'  in a:
    j = a.index('[')
    k = a.index(']')
    b = a.replace(a[j:k + 1], str(int(eval(a[j + 1:k]))))
    m = b.index('{')
    n = b.index('}')
    c = b.replace(b[m:n + 1], str(int(eval(b[m + 1:n]))))
    print(eval(c))
发表于 2022-08-23 22:38:56 回复(0)
算法是python栈的模板,
但是处理输入太难了,既要考虑负数,还要考虑多位数,参考了两位大佬,终于ac了。
算法是python栈的模板,
但是处理输入太难了,既要考虑负数,还要考虑多位数,参考了两位大佬,终于ac了。
#中缀转后缀
class Stack:
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []

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

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

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

def infixToPostfix(infixexpr):  #中缀转后缀
    prec = {}
    prec['*'] = 3   #定义运算符的优先级
    prec['/'] = 3
    prec['+'] = 2
    prec['-'] = 2
    prec['('] = 1
    opStack = Stack()    #空栈用来暂存操作符
    postfixList = []    #空表接收后缀表达式
    for token in tokenList:
        if token.isdigit() :
            postfixList.append(token)
        elif token == '(' :
            opStack.push(token)
        elif token == ')' :
            toptoken = opStack.pop()
            while toptoken != '(':
                postfixList.append(toptoken)
                toptoken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()]) >= prec[token]:
                postfixList.append(opStack.pop())
            opStack.push(token)
    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return ' '.join(postfixList)

def postfixEval(postfixExpr):   #计算后缀表达式
    operandStack = Stack()
    tokenList = postfixExpr.split()
    for token in tokenList:
        if token.isdigit():
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)
    return operandStack.pop()

def doMath(op,op1,op2):     #数***算
    if op == '*':
        return op1*op2
    elif op == '/':
        return op1/op2
    elif op == '+':
        return op1+op2
    else:
        return op1-op2


str = input()
s = str.replace("{", "(").replace("}", ")").replace("]", ")").replace("[", "(").replace(" ", "")
for simbol in ["+", "-", "*", "/", "(", ")"]:
    s = s.replace(simbol, " {} ".format(simbol))
s = s.split()
tokenList = []
for i in range(len(s)):
    if s[i] == '-' and s[i-1] == '(':
        tokenList.append('0')
        tokenList.append(s[i])
    else:
        tokenList.append(s[i])

postfixExpr =  infixToPostfix(tokenList)

print(int(postfixEval(postfixExpr)))

发表于 2022-07-05 20:02:30 回复(0)
while True:
    try:
        raw = input()
        raw = raw.replace("[", "(").replace("]", ")").replace("{", "(").replace("}", ")")
        print(eval(raw))
    except Exception as e:
        break
发表于 2022-06-24 23:15:47 回复(0)
while True:
    try:
        s=input()
        s=s.replace('{', '(')
        s=s.replace("}",")")
        s=s.replace("[","(")
        s=s.replace("]",")")
        print(int(eval(s))) # eval 去掉'',eval是Python的一个内置函数,
        #这个函数的作用是,返回传入字符串的表达式的结果。
    except:
        break

发表于 2022-05-04 02:13:28 回复(0)

print(int(eval(input().replace("{", "(").replace("}", ")").replace("[", "(").replace("]", ")"))))

发表于 2022-04-27 17:09:10 回复(0)
line = input()
line = line.replace('{', '(')
line = line.replace('}', ')')
line = line.replace('[', '(')
line = line.replace(']', ')')
print(int(eval(line)))

发表于 2022-04-03 23:57:38 回复(1)
s = input("")
res = ''
for i in range(len(s)):
    try:
        int(s[i])
        res += int(s[i])
    except:
        if s[i] in ["(", "{", "["]:
            res += ("(")
        elif s[i] in [")", "}", "]"]:
            res += (")")
        else:
            res += (s[i])
print(eval(res))

发表于 2022-03-03 16:42:44 回复(0)
import re
a = input()
b = re.sub(r'\{|\[', '(', a)
c = re.sub(r'\}|\]', ')', b)
print(int(eval(c)))

发表于 2022-02-28 00:54:22 回复(0)
data = input().replace('/','//').replace('{','(').replace('}',')').replace('[','(').replace(']',')')
print(eval(data))
发表于 2022-02-23 23:26:38 回复(0)