Skip to content

Commit 6cd6af6

Browse files
committed
后缀表达式
1 parent 74808f5 commit 6cd6af6

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,16 @@ Success
8585
~~~python轮子很强大~~~
8686
```
8787

88+
### rpn.py 逆波兰表达式 python 版实现
89+
逆波兰表达式被广泛应用于编译原理中,是一种是由波兰数学家扬·武卡谢维奇1920年引入的数学表达式方式,在逆波兰记法中,
90+
所有操作符置于操作数的后面,因此也被称为后缀表示法。逆波兰记法不需要括号来标识操作符的优先级。
91+
以利用堆栈结构减少计算机内存访问。
92+
➜ Py git:(master) ✗ python rpn.py
93+
['11111111111111', '9999999999999', '*', '99', '12', '4', '/', '-', '10', '+', '+']
94+
True 111111111111098888888888995 111111111111098888888888995
95+
True 326 326
96+
➜ Py git:(master) ✗
97+
8898

8999
### dispatch.py 轮转队列
90100
```

rpn.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# -*- coding: utf-8 -*-
2+
# @Author: lock
3+
# @Date: 2017-06-26 15:51:28
4+
# @Last Modified by: lock
5+
# @Last Modified time: 2017-06-26 15:55:53
6+
def calc(s):
7+
if type(s) != list:s = s.split(' ')
8+
operaList = ['+', '-', '*', '/'];
9+
for key, item in enumerate(s):
10+
if item in operaList:
11+
val = eval(s[key - 2] + item + s[key - 1])
12+
s.insert(key - 2, str(val))
13+
for x in ['1','2','3']:del s[key - 1]
14+
calc(s)
15+
return sum(map(eval, s))
16+
def translate(calcStr):
17+
element, calcList,s,stackStr,i = '', [],[],[],0
18+
for key,item in enumerate(calcStr):
19+
if item.isdigit():
20+
element = element + item
21+
if key == len(calcStr)-1:calcList.append(element)
22+
else:
23+
if element != '':
24+
calcList.append(element)
25+
element = ''
26+
if item in ['+', '-', '*', '/', '(', ')']:
27+
calcList.append(item)
28+
calcList.insert(0,'(')
29+
calcList.append(')')
30+
calcList.append('#')
31+
while calcList[i] != "#":
32+
if (calcList[i].isdigit()):
33+
stackStr.append(calcList[i])
34+
elif calcList[i] == '(':
35+
s.append(calcList[i])
36+
elif calcList[i] == ')':
37+
while s[-1] != '(':
38+
stackStr.append(s.pop())
39+
s.pop()
40+
elif calcList[i] in ['+', '-']:
41+
while s[-1] != '(':
42+
stackStr.append(s.pop())
43+
s.append(calcList[i])
44+
elif calcList[i] in ['*', '/']:
45+
while s[-1] in ['*', '/']:
46+
stackStr.append(s.pop())
47+
s.append(calcList[i])
48+
i = i + 1
49+
return stackStr
50+
if __name__ == '__main__':
51+
s = '11111111111111*9999999999999+(99-(12/4)+10)'
52+
print translate(s)
53+
print str(calc(translate('11111111111111*9999999999999+(99-(12/4)+10)'))) == str(11111111111111*9999999999999+(99-(12/4)+10)),str(calc(translate(s))) , str(11111111111111*9999999999999+(99-(12/4)+10))
54+
print str(calc(translate('12+1+12+33*9+4'))) == str(12+1+12+33*9+4),str(calc(translate('12+1+12+33*9+4'))) , str(12+1+12+33*9+4)
55+
56+
57+

0 commit comments

Comments
 (0)