Skip to content

Commit b5deb04

Browse files
committed
过程方式模拟栈的算法
0 parents  commit b5deb04

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.vscode/

file.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
65+1-5*
2+
27*21-5//
3+
13+24+253-

stack.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
with open('file.txt', 'r') as f:
3+
for line in f.readlines():
4+
# 去除line首尾的空格或换行符 这里主要是去除'\n'
5+
line = line.strip()
6+
print('*'*20)
7+
print(line)
8+
# 定义一个空栈
9+
stack = []
10+
# 从头到尾遍历line的每一个字符存到变量c中
11+
for c in line:
12+
# 如果字符c是个数
13+
if c.isnumeric():
14+
# 将c的内容push到栈中
15+
stack.append(c)
16+
# 如果c为算数符号
17+
elif c == '+' or c == '-' or c == '*' or c == '/':
18+
# 将栈顶(最后入栈)的内容存入变量a1中
19+
a1 = stack[len(stack) - 1]
20+
# 将栈顶的内容弹出(删除最后一个入栈的内容)
21+
stack.pop()
22+
# 同样的操作得到第二个数
23+
a2 = stack[len(stack)-1]
24+
stack.pop()
25+
# 将a2,c,a1拼接成字符串表达式,并用eval方法计算这个表达式,结果存入result
26+
result = eval(a2+c+a1)
27+
print(a2, c, a1, '=', result)
28+
stack.append(str(result))
29+
print(stack[len(stack) - 1])
30+
stack.pop()
31+
if len(stack):
32+
print('Error!')

0 commit comments

Comments
 (0)