f698:後序運算式
Code
Correct Code
#data="6 3 / 1 4 - * 3 + 8 -"
def postfix(instr):
list1=list(map(str,instr.split()))
stack=[]
#print("len=",len(list1))
for i in range(len(list1)):
if list1[i] not in "+-*/":
stack.append(list1[i])
else:
a=stack.pop()
b=stack.pop()
ope=b+list1[i]+a
#print("a=",a,"b=",b)
#print("ope=",ope)
stack.append(str(int(eval(ope))))
#print(stack)
return stack[0]
data=str(input())
ans=postfix(data)
print(ans)
不能用string直接算
如果用string直接算的話,長度和元素會算入空白!所以必須轉換成list,切出可用元素。
例如下面的code,data長度是5,而a會是空白
data="2 1 -"
print("data=",data)
#print("outer len",len(data))
def postfix (instr):
stack=[]
print("len=",len(instr))
for i in range(len(instr)):
if instr[i] not in "+-*/":
stack.append(instr[i])
else:
a=stack.pop()
b=stack.pop()
ope=b+instr[i]+a
print("a=",a,"b=",b)
print("ope=",ope)
stack.append(str(eval(ope)))
print(stack)
return stack[0]
ans=postfix(data)
print(ans)