计算算术表达式的程序
A program to evaluate arithmetic expression
这是一个有趣的问题,我还没有设法解决。
给定 Reverse Polish Notation 中的一个算术表达式,编写一个程序来计算它。
表达式以数字和操作数的列表形式给出。例如 [5, 3, '+']
应该 return 5 + 3 = 8
.
例如,
[15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']
应该 return 5
因为它等同于 ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5
.
这段代码可以完成工作:
ops = {
"+": (lambda a, b: a + b),
"-": (lambda a, b: a - b),
"*": (lambda a, b: a * b),
"/": (lambda a, b: a / b)
}
def pol(tokens):
stack = []
for token in tokens:
# Check if the current element is an operator
if token in ops:
# Take the last two elements from the list
arg2 = stack.pop()
arg1 = stack.pop()
# Execute an operation based on the current operator
result = ops[token](arg1, arg2)
# Append the result to the list in order to keep working with it
stack.append(result)
else:
# If it is a number, just append in to the list
stack.append(int(token))
return stack.pop()
print(pol([15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']))
尝试用字符串方法解决。
import re
d = [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']
ops = {
"+": (lambda a, b: a + b),
"-": (lambda a, b: a - b),
"*": (lambda a, b: a * b),
"/": (lambda a, b: a / b)
}
while len(d) > 1:
s_d = ' '.join(map(str, d))
l_d = re.findall(r'\d+ \d+ \W', s_d)
# print(l_d)
for l1 in l_d:
l = l1.split(' ')
a = int(ops[l[-1]](int(l[0]),int(l[1])))
s_d = s_d.replace(l1, str(int(a)))
d = s_d.split()
print(d)
print('----------------------')
print(d[0])
这是一个有趣的问题,我还没有设法解决。
给定 Reverse Polish Notation 中的一个算术表达式,编写一个程序来计算它。
表达式以数字和操作数的列表形式给出。例如 [5, 3, '+']
应该 return 5 + 3 = 8
.
例如,
[15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']
应该 return 5
因为它等同于 ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5
.
这段代码可以完成工作:
ops = {
"+": (lambda a, b: a + b),
"-": (lambda a, b: a - b),
"*": (lambda a, b: a * b),
"/": (lambda a, b: a / b)
}
def pol(tokens):
stack = []
for token in tokens:
# Check if the current element is an operator
if token in ops:
# Take the last two elements from the list
arg2 = stack.pop()
arg1 = stack.pop()
# Execute an operation based on the current operator
result = ops[token](arg1, arg2)
# Append the result to the list in order to keep working with it
stack.append(result)
else:
# If it is a number, just append in to the list
stack.append(int(token))
return stack.pop()
print(pol([15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']))
尝试用字符串方法解决。
import re
d = [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']
ops = {
"+": (lambda a, b: a + b),
"-": (lambda a, b: a - b),
"*": (lambda a, b: a * b),
"/": (lambda a, b: a / b)
}
while len(d) > 1:
s_d = ' '.join(map(str, d))
l_d = re.findall(r'\d+ \d+ \W', s_d)
# print(l_d)
for l1 in l_d:
l = l1.split(' ')
a = int(ops[l[-1]](int(l[0]),int(l[1])))
s_d = s_d.replace(l1, str(int(a)))
d = s_d.split()
print(d)
print('----------------------')
print(d[0])