目录
题目
代码
碎碎念:我用来复习栈的,刷了巨长时间,一直runtine error,编译直接就没有过。
好家伙,然后发现是数据给的不够严谨,左右两端有空格,使用strip()处理一下就好了。
class stack:def __init__(self
,*args
):self
.items
= [i
for i
in args
]def __str__(self
):return str(self
.items
)def push(self
,item
):self
.items
.append
(item
)def pop(self
):return self
.items
.pop
()def is_empty(self
):return self
.items
== []def peek(self
):return self
.items
[-1]def size(self
):return len(self
.items
)def show(self
):return self
.items
def clear(self
):self
.items
= []
def change_expression(s
: str):dic
= {"(": 0,"^": 3,"*": 2,"/": 2," ": 1,"-": 1}stack
= stack
() res
= [] for i
in s
:if i
in [' ', '-', '*', '/', '^']:while (not stack
.is_empty
() and dic
[stack
.peek
()] >= dic
[i
]):res
.append
(stack
.pop
())stack
.push
(i
)elif i
== '(':stack
.push
(i
)elif i
== ')':top_token
= stack
.pop
()while (top_token
!= '('):res
.append
(top_token
)top_token
= stack
.pop
()else:res
.append
(i
)while not stack
.is_empty
():res
.append
(stack
.pop
())return " ".join
(res
)def calc_postfix_expression(s
: str):stack
= stack
()temp
= list(s
)index
= 0for i
in s
:if i
in "0123456789":stack
.push
(int(i
))else:op2
= stack
.pop
()op1
= stack
.pop
()ans
= do_math
(i
, op1
, op2
)stack
.push
(ans
)before
= temp
[0:index
-2]before
.append
(str(ans
))out
= before temp
[index
1:]temp
= outindex
= index
- 2print(" ".join
(out
))index
= 1return stack
.pop
()def do_math(op
, op1
, op2
):if op
== ' ':return op1op2
elif op
== '-':return op1
-op2
elif op
== '*':return op1
*op2
elif op
== '/':return op1
//op2
elif op
== '^':return op1
**op2
if __name__
== '__main__':expression
= input().strip
()res
= change_expression
(expression
)print(res
) calc_postfix_expression
(res
.replace
(" ", ""))
ac截图
总结
以上是凯发k8官方网为你收集整理的【python】洛谷 p1175_表达式的转换(逆波兰式、中缀表达式、后缀表达式、栈)的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。