首页 > 试题广场 >

四则运算

[编程题]四则运算
  • 热度指数:122401 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
输入一个表达式(用字符串表示),求这个表达式的值。
保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。

数据范围:表达式计算结果和过程中满足 ,字符串长度满足


输入描述:

输入一个算术表达式



输出描述:

得到计算结果

示例1

输入

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

输出

25
s = input().strip()


s = s.replace('{', '(')
s = s.replace('}', ')')
s = s.replace('[', '(')
s = s.replace(']', ')')
s = s.replace('/', '//')

print(eval(s))

发表于 2021-05-04 16:07:06 回复(1)
# 字符串表达式求值都使用python3 的 eval() 和 input()函数

# input() 接收一个标准输入,为字符串类型
# eval() 计算字符串表达式的值
print(eval(input()))


发表于 2021-04-22 10:18:55 回复(0)
print(int(eval(input())))
发表于 2021-03-30 16:02:32 回复(0)
data = raw_input()
str1 = data.replace('{', '(')
str2 = str1.replace('}', ')')
str3 = str2.replace('[', '(')
str4 = str3.replace(']', ')')
print eval(str4)
发表于 2020-12-16 11:27:32 回复(0)
while True:
    try:
        print(eval(input()))
    except:
        break
        

发表于 2020-11-13 18:09:35 回复(1)
示例有中括号和大括号,用例应该没出现这两种括号。正确的做法是用小括号替换掉中、大括号。
同时示例输出整数,如果有除法,就会产生小数,需要用int转换。
while True:
    try:
        exp = input().replace('{', '(').replace('}', ')').replace('[', '(').replace(']', ')')
        result = eval(exp)
        print(int(result))
    except EOFError:
        break


发表于 2020-09-30 17:32:24 回复(0)
import operator

OPS = {'+': 0, '-': 0, '*' : 1, '/': 1, '{': 2, '[': 3, '(':4 }
OPEN_OPS = {'{', '[', '('}
CLOSE_OPS = {'}': '{', ']':'[', ')':'('}
op = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}


def tokenize(expression):
	token = ""
	for c in expression:
		if not c.isdigit():
			if token != "":
				yield token
				token = ""
			yield c
		else:
			token += c

	if token:
		yield token


def infix_to_postfix(expression: str):
	op_stack = []
	res = []
	for c in tokenize(expression):
		# 1. 如果是数字直接 append res
		if c.isdigit():
			res.append(c)

		# 2. 如果是操作符
		elif c in OPS:
			# 2.1 如果栈为空 或 操作符为开括号 或 等级大于栈顶操等级 或 栈顶为开括号, 加入op栈
			if len(op_stack) == 0&nbs***bsp;c in OPEN_OPS&nbs***bsp;op_stack[-1] in OPEN_OPS&nbs***bsp;OPS[c] > OPS[op_stack[-1]]:
				op_stack.append(c)

			# 2.2 如果操作符等级小于栈顶操作符等级, 先出栈**栈, 直到栈顶大于操作符等级为止
			else:
				while len(op_stack) > 0 and op_stack[-1] not in OPEN_OPS and OPS[c] <= OPS[op_stack[-1]]:
					res.append(op_stack[-1])
					op_stack.pop()
				op_stack.append(c)

		# 3. 如果是结束括号
		elif c in CLOSE_OPS:
			# 持续出栈, 直到遇到匹配的开始括号
			while len(op_stack) > 0 and op_stack[-1] != CLOSE_OPS[c]:
				res.append(op_stack[-1])
				op_stack.pop()

			if len(op_stack) > 0 and op_stack[-1] == CLOSE_OPS[c]:
				op_stack.pop()

	while len(op_stack) > 0:
		res.append(op_stack[-1])
		op_stack.pop()

	return res


def evaluate(postfix: list):
	value_stack = []
	num1, num2 = None, None
	for token in postfix:
		if token.isdigit():
			if num1 is None:
				num1 = int(token)
				continue
			if num2 is None:
				num2 = int(token)
				continue

			value_stack.append(num1)
			num1, num2 = num2, int(token)

		elif token in op:
			if num1 is not None and num2 is None and len(value_stack) > 0:
				num1, num2 = value_stack.pop(), num1

			if num1 is not None and num2 is not None:
				num1 = op[token](num1, num2)
				num2 = None
				continue

	return num1

发表于 2020-09-15 17:00:40 回复(0)
 原理参考博文:https://blog.csdn.net/Antineutrino/article/details/6763722
本质:将中缀表达式 转化为计算机容易计算的前缀表达式或后缀表达式
# 前缀表达式: 运算符栈S1【栈顶优先级更高】 + 存储中间结果栈S2【从右往左扫描中缀表达式数字】
简单过程描述:
# 优先级较高的操作符直接入栈S1,右括号直接入栈S1,遇到左括号则使使碰到右括号之前的操作符弹出S1放进S2
# 左括号右括号均弹出
# 最终S1为空栈,S2为只有加减乘除和数字的前缀表达式的栈
# 将S2进行运算和结果处理:从右往左扫描,碰到数字就入栈S3,碰到操作符就弹出S2栈顶的两个元素进行数***算然后将计算结果入栈S3,以此运算,S3栈留下的唯一数字即结果。

# 本来考虑计算的优先顺序 圆括号> 中括号> 大括号,但是实质上不需要考虑这么多括号,把中括号大括号都替代成圆括号

import collections


def cat(exe_in):
    limao = exe_in.replace('{', '(').replace('}', ')').replace('[', '(').replace(']', ')')
    puc = [i for i in limao.strip()]
    # print(puc)
    # 如果碰到负数,在负数前加0
    puc_copy = []

    tmp = []   # 临时存储数字以合并个位数以上的数字

    if puc[0] == '-':
        puc_copy.append('0')
        puc_copy.append('-')
    elif puc[0].isdigit():
        tmp.append(puc[0])
    else:
        puc_copy.append(puc[0])
    # 十位数以上数字字符串合并

    for i in range(1, len(puc)+1):
        # print(puc[i])
        if i < len(puc):
            if puc[i] == '-' and puc[i - 1] == '(':
                puc_copy.append('0')
                puc_copy.append('-')
            elif puc[i].isdigit():
                tmp.append(puc[i])
            elif tmp:
                # print(tmp)
                combine = ''.join(tmp)
                puc_copy.append(combine)
                puc_copy.append(puc[i])
                tmp = []
            else:
                puc_copy.append(puc[i])
        else:
            if tmp:     # 表达式末尾的数字字符串
                combine = ''.join(tmp)
                puc_copy.append(combine)

    return puc_copy

def exe_transfer(exep):
    # 创建字典进行优先级比较
    coll_dict = collections.OrderedDict()
    coll_dict = {'+': 5, '-': 5, '*': 4, '/': 4, '{': 3, '}': 3, '[': 2, ']': 2, '(': 1, ')': 1}
    # 中缀表达式转化为前缀表达式
    # 运算符栈S1【栈顶优先级更高】 + 存储中间结果栈S2【从右往左扫描中缀表达式数字】
    exep.reverse()
    S1, S2 = [], []
    for i in exep:
        # print('-----------')
        # print(i)
        # print(S1)
        # print(S2)
        # 判断字符串是否为数字
        if i.isdigit():
            S2.append(int(i))
        # 操作符
        else:
            if S1 == []&nbs***bsp;S1 == ')':  # 如果S1为空或者右括号直接入栈
                S1.append(i)
            elif S1[-1] == ')':  # 如果S1栈顶为右括号直接入栈
                S1.append(i)
            elif i == '(':  # 左括号带走右括号,并将他们之间的值推入S2
                for j in range(len(S1) - 1, -1, -1):
                    if S1[j] != ')':
                        S2.append(S1[j])
                        S1.pop()
                    else:
                        S1.pop()
                        break
            elif coll_dict[i] <= coll_dict[S1[-1]]:  # 如果即将入栈的优先级较高直接入栈
                S1.append(i)
            # 有点小问题
            else:  # 如果即将入栈的优先级较低
                S2.append(S1[-1])
                S1.pop()

                for j in range(len(S1)+1):
                    if S1 == []:
                        S1.append(i)
                        break
                    if S1[-1] == ')':
                        S1.append(i)
                        break
                    if coll_dict[i] > coll_dict[S1[-1]]:
                        S2.append(S1[-1])
                        S1.pop()
                    else:
                        S1.append(i)
                        break

    # S1剩余部分
    for k in range(len(S1)):
        S2.append(S1[-1])
        S1.pop()
    # 返回前缀表达式
    return S2


# S2计算函数
# 从右往左扫,碰到数字就入栈,碰到操作符就弹出栈顶的两个元素进行计算然后将计算结果入栈
def exe_cacul(prefix):
    S3 = []
    for i in prefix:
        # print(i)

        if i == '+'&nbs***bsp;i == '-'&nbs***bsp;i == '*'&nbs***bsp;i == '/':
            if i == '+':
                answer = S3[-1]+S3[-2]
            elif i == '-':
                answer = S3[-1] - S3[-2]
            elif i == '*':
                answer = S3[-1] * S3[-2]
            else:
                answer = S3[-1] / S3[-2]
            S3.pop()
            S3.pop()
            S3.append(answer)
        else:      # 数字直接入栈
            S3.append(i)
        # print(S3)
    return S3[0]


if __name__ == '__main__':

    exe_in = input()

    puc_copy = cat(exe_in)
    # print(puc_copy)
    prefix = exe_transfer(puc_copy)

    # print(prefix)
    print(int(exe_cacul(prefix)))


发表于 2020-09-10 17:20:07 回复(0)
def format_line(line, opt_in, opt_out):
    while opt_in in line:
        add = False
        for i in line:
            if i == opt_in:
                add = True
                add_str = ""
                continue
            if i == opt_out:
                add_sum = eval(add_str)
                old_str = opt_in + add_str + opt_out
                line = line.replace(old_str, str(add_sum))
                if line.count(opt_in) == 1 and line.startswith(opt_in):
                    return line
                break
            if add:
                add_str += i
    return line


while True:
    try:
        line = str(input())
        line = line.replace('/', '//')
        line = format_line(line, "(", ")")
        line = format_line(line, "[", "]")
        line = format_line(line, "{", "}")
        result = eval(line)
        print(result)
    except BaseException:
        break
发表于 2020-09-06 00:12:04 回复(0)
while True:
    try:
        print(eval(input().replace('[','(').replace(']',')').replace('{','(').replace('}',')')))
    except:
        break

发表于 2020-08-31 16:24:02 回复(0)

四则运算
看了一些解法后,自己实现了一遍

  1. 将中序表达式转变为后续表达式
  2. 对负数的处理,增加了一个标识符flag, 判断-号是运算符还是负号,如果是运算符则正常处理,如果是负号,则令flag=-1, 负号后面的整数取:flag*n,即为负值,然后continue返回,不把-号当作运算符处理;
  3. 转变为后续表达式后,正常计算值即可
  4. 中序,前后,后续的转变参考 ** Python数据结构与算法分析(第2版)3.3栈**
    class Solution:
     def houxu(self, s: str):
         s.replace('[', '(')
         s.replace('{', '(')
         s.replace(']', ')')
         s.replace('}', ')')
         map_dict = {
             "*": 3,
             "/": 3,
             "+": 2,
             "-": 2,
             "(": 1
         }
         digi_stack = []
         sigh_stack = []
         flag = 1
         j = -1
         for i in range(len(s)):
             if i < j:
                 continue
             if s[i].isdigit():
                 j = i
                 while j < len(s) and s[j].isdigit():
                     j += 1
                 digi_stack.append(flag * int(s[i:j]))
             elif s[i] == '(':
                 sigh_stack.append(s[i])
             elif s[i] in ['+', "-", "*", "/"]:
                 if s[i] == "-":
                     if i == 0 or s[i - 1] == "(" or s[i - 1] in ['+', "-", "*", "/"]:
                         flag = -1
                         continue
                 flag = 1
                 while sigh_stack and map_dict[sigh_stack[-1]] >= map_dict[s[i]]:
                     digi_stack.append(sigh_stack.pop())
                 sigh_stack.append(s[i])
             elif s[i] == ")":
                 temp = sigh_stack.pop()
                 while temp != "(":
                     digi_stack.append(temp)
                     temp = sigh_stack.pop()
         while sigh_stack:
             digi_stack.append(sigh_stack.pop())
         # res = " ".join(digi_stack)
         return digi_stack
     def calcute(self, a, b, c):
         if c == "+": return a + b
         if c == "-": return a - b
         if c == "*": return a * b
         if c == "/": return a // b
     def calcuteResults(self, s):
         digi_stack = self.houxu(s)
         di_stack = []
         for x in digi_stack:
             if isinstance(x, int):
                 di_stack.append(x)
             else:
                 b = di_stack.pop()
                 a = di_stack.pop()
                 di_stack.append(self.calcute(a, b, x))
         print(di_stack[0]) 
    s = input()
    solu = Solution()
    solu.calcuteResults(s)
发表于 2020-08-08 16:21:35 回复(0)
str = list(input()) for i in range(len(str)): if str[i] == '{' or str[i] == '[':
        str[i] = '('  elif str[i] == '}' or str[i] == ']':
        str[i] = ')'  print(eval("".join(str)))
发表于 2020-08-05 14:35:27 回复(0)
while 1:
    try:
        a = input()
        b = a.replace('[','(').replace(']',')')
        c = b.replace('{','(').replace('}',')')
        print(eval(c))
    except:
        break
        
eval函数实现此功能需要替换中括号和大括号
发表于 2020-05-04 20:18:24 回复(0)
#!usr/bin/env python
while 1:
    try:
        s = input()
        print s
    except:
        break

发表于 2020-04-12 16:27:09 回复(0)
python ac代码如下:
老老实实按后缀表达式解法来写的==
def pri(a):
    if a == '(':
        return 1
    elif a == '+' or a == '-':
        return 2
    elif a == '*' or a == '/':
        return 3

def cal(a,b,c):
    if c == '-':
        return int(a) - int(b)
    elif c == '+':
        return  int(a) + int(b)
    elif c == '*':
        return int(a) * int(b)
    elif c == '/':
        return int(a)//int(b)
while True:
    try:
        s = input().strip()
        data = []
        yunsuan = []
        s = s.replace('[','(')
        s = s.replace('{','(')
        s = s.replace('}',')')
        s = s.replace(']',')')
        i = 0
        while i < len(s):
            if s[i].isdigit():   #处理数字
                j = i
                while j < len(s) and s[j].isdigit() :
                    j = j + 1
                data.append(s[i:j])
                i = j
            elif s[i] in ['+','-','*','/']:
                if s[i] == '-':   #处理负数的情况,在-前面加上0
                    if i==0 or not s[i-1].isdigit() and s[i-1]!=')':
                        s = list(s)
                        s.insert(i,'0')
                        s = ''.join(s)
                        continue
                if not yunsuan:
                    yunsuan.append(s[i])
                else:
                    if pri(s[i]) > pri(yunsuan[-1]):
                        yunsuan.append(s[i])
                    else:
                        while yunsuan and pri(s[i]) <= pri(yunsuan[-1]):
                            sym = yunsuan.pop()
                            data.append(sym)
                        yunsuan.append(s[i])
                i = i+ 1
            else:
                if s[i] == '(':
                    yunsuan.append(s[i])
                else:
                    while yunsuan[-1] != '(':
                        data.append(yunsuan.pop())
                    yunsuan.pop()
                i = i + 1
        while yunsuan:
            data.append(yunsuan.pop())
        #print(data)
        j = 0
        while len(data) != 1:
            try:
                fl = int(data[j])
                j += 1
            except:
                t1 = data.pop(j)
                t2 = data.pop(j-1)
                data[j-2] = str(cal(data[j-2],t2,t1))
                j = j - 1
        print(data[0])
    except:
        break
编辑于 2020-04-11 17:33:32 回复(1)
print(int(eval(input().replace("{","(").replace("}",")").replace("[","(").replace("]",")"))))

发表于 2020-02-20 22:38:43 回复(0)
print(eval(str(input())))
发表于 2020-02-19 08:22:04 回复(0)
input_str = input()
re = eval(input_str)
print(re)

发表于 2019-10-17 21:30:15 回复(0)

问题信息

难度:
24条回答 46036浏览

热门推荐

通过挑战的用户

查看代码