表达式求值
作者:互联网
# 中缀表达式转为后缀表达式
def func1(s: str):
s1temp = []
s2temp = []
for i in s.split():
if i.isdigit():
s1temp.append(i)
elif i in '*/+-':
s2temp.append(i)
elif i in ')':
s1temp.append(s2temp.pop())
return " ".join(s1temp)
# 后缀表达式求值
def func2(s: str):
s1temp = []
for i in s.split():
if i.isdigit():
s1temp.append(i)
else:
s2 = s1temp.pop()
s1 = s1temp.pop()
s1temp.append(eval(f'{s1}{i}{s2}'))
return s1temp[0]
if __name__ == '__main__':
s1 = '( 2 + ( ( 4 * 8 ) / ( 2 + 2 ) ) )' # 2 4 8 * 2 2 + / +
s2 = '23 22 + 2 4 * -' # 23 + 22 - 2 * 4
s3 = '0 9 -'
print(func1(s1))
print(func2(s2))
print(func2(s3))
标签:__,s2,s1,表达式,求值,s1temp,append 来源: https://www.cnblogs.com/bigcoolcool/p/16209550.html