正则表达式计算 origin = "1 - 2 * ( ( 60 - 30 + ( -40.0 / 5 ) * ( 9 - 2 * 5 / 3 + 7 / 3 * 99 / 4 * 2998 + 10 * 568 / 14 )) - ( - 4 * 3 ) / ( 16 - 3 * 2))"

 1 #!/usr/bin/env python
 2 import re
 3 def f1(arg):
 4 
 5     return 1
 6 
 7 origin = "1 - 2 * ( ( 60 - 30 + ( -40.0 / 5 ) * ( 9 - 2 * 5 / 3 + 7 / 3 * 99 / 4 * 2998 + 10 * 568 / 14 )) - ( - 4 * 3 ) / ( 16 - 3 * 2))"
 8 print(eval(origin))
 9 while True:
10     print(origin)
11     ret = re.split("\(([^()]+)\)", origin,1)
12     if len(ret) == 3:
13         before = ret[0]
14         content = ret[1]
15         after = ret[2]
16         r = f1(content)
17         new_str = before + str(r) + after
18         origin = new_str
19     else:
20         final = f1(origin)
21         print(final)
22         break

 

posted @ 2017-02-13 20:35  失落的黎明  阅读(1047)  评论(0编辑  收藏  举报