Python 学习笔记-12

Python 学习笔记-12:

  1. 计算器

利用Python的正则表达式写的简易计算器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# author : Ryoma
# time : 17:39

import re

def add(string):
equ = string
flag = True
while flag:
is_right = re.search('[\-]?\d+\.?\d*\+[\-]?\d+\.?\d*', equ)
if is_right:
old = is_right.group()
# 计算加法
nums = old.split('+')
sum = float(nums[0]) + float(nums[1])
new = str(sum)
equ = equ.replace(old,new)
else:
flag = False
return equ

def reduce(string):
equ = string
flag = True
while flag:
is_right = re.search('[\-]?\d+\.?\d*-[\-]?\d+\.?\d*', equ)
if is_right:
old = is_right.group()
# 计算减法
count = len(re.findall('-',old))
if count==1:
nums = old.split('-')
sum = float(nums[0]) - float(nums[1])
new = str(sum)
equ = equ.replace(old, new)
elif count==2:
nums = old.split('-')
sum = - float(nums[1]) - float(nums[2])
new = str(sum)
equ = equ.replace(old, new)
else:
flag = False
return equ

def ride(string):
equ = string
flag = True
while flag:
is_right = re.search('[\-]?\d+\.?\d*\*[\-]?\d+\.?\d*', equ)
if is_right:
old = is_right.group()
# 计算乘法
nums = old.split('*')
sum = float(nums[0]) * float(nums[1])
new = str(sum)
equ = equ.replace(old,new)
else:
flag = False
return equ

def divide(string):
equ = string
flag = True
while flag:
is_right = re.search('[\-]?\d+\.?\d*/[\-]?\d+\.?\d*', equ)
if is_right:
old = is_right.group()
# 计算除法
nums = old.split('/')
if nums[1] == '0':
exit('0不能做被除数!')
sum = float(nums[0]) / float(nums[1])
new = str(sum)
equ = equ.replace(old,new)
else:
flag = False
return equ

# 判断优先级 按照优先级进行计算:括号>乘除法>加减法
def pri(equ):
flag = True
while flag:
# 查找最里层括号
ret = re.search('\([^()]+\)', equ)
if ret:
# 记录查找的式子
old = ret.group()
# 去除括号
new = old.replace('(', '')
new = new.replace(')', '')
# 计算-先乘除后加减
new = ride(new)
new = divide(new)
new = add(new)
new = reduce(new)
# 替换方程式
equ = equ.replace(old, new)
else:
flag = False
else:
equ = ride(equ)
equ = divide(equ)
equ = add(equ)
equ = reduce(equ)

return equ

# 格式处理
def check(equ):
equ = equ.replace(' ','')
if len(re.findall('[^0-9\-+/*\(\).]', equ)):
print("请输入正确的表达式!")
elif not equ.count('(') == equ.count(')'):
print("存在未闭合的括号!")
else:
equ = pri(equ)
return equ

if __name__ == '__main__':
print("欢迎使用计算器".center(50,'-'))
while 1:
equ = input("输入你要计算的式子:")
equ = check(equ)
print(equ)