admin 管理员组文章数量: 1086019
2024年3月27日发(作者:mysql安装必须安装vc吗)
63 ans = a + b
64 elif operator == '-':
65 ans = a - b
66 elif operator == '*':
67 ans = a * b
68 elif operator == '/':
69 if b == 0:
70 ans = "VALUE ERROR"
71 else:
72 ans = a / b
73 elif operator == '^':
74 if a == 0 and b == 0:
75 ans = "VALUE ERROR"
76 else:
77 ans = a ** b
78
79 return ans
80
81 def calc(exp):
82 """
83 Calculate the ans of exp
84 """
85 exp += '#'
86 operSet = "+-*/^()#"
87 stackOfOperator, stackOfNum = ['#'], []
88 pos, ans, index, length = 0, 0, 0, len(exp)
89 while index < length:
90 e = exp[index]
91 if e in operSet:
92 # calc according to the prior
93 topOperator = ()
94 compare = precede(topOperator, e)
95 if compare == '>':
96 try:
97 b = ()
98 a = ()
99 except:
100 return "FORMAT ERROR"
101 ans = operate(a, b, topOperator)
102 if ans == "VALUE ERROR":
103 return ans
104 else:
105 (ans)
106 elif compare == '<':
107 (topOperator)
108 (e)
109 index += 1
110 elif compare == '=':
111 index += 1
112 elif compare == ' ':
113 return "FORMAT ERROR"
114 else:
115 # get the next num
116 pos = index
117 while not exp[index] in operSet:
118 index += 1
119 temp = exp[pos:index]
120
121 # delete all 0 of float in the end
122 last = index - 1
123 if '.' in temp:
124 while exp[last] == '0':
125 last -= 1
126 temp = exp[pos:last + 1]
127
128 try:
129 temp = Decimal(temp)
130 except:
131 return "INPUT ERROR"
132 (temp)
133
134 if len(stackOfNum) == 1 and stackOfOperator == []:
135 return ()
136 else:
137 return "INPUT ERROR"
138
139 if __name__ == "__main__":
140 # get the exp
141 exp = argv[1]
142
143 # set the precision
144 getcontext().prec = 10
145
146 # delete blanks
版权声明:本文标题:用Python3实现表达式求值 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1711537153a598879.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论