无需python中内置函数即可评估一个数学表达式的程序
假设我们有一个用(+,-,*,/)表示一个数学表达式的字符串,这里/表示整数除法,我们必须在不使用任何内置函数的情况下求值并返回结果。
因此,如果输入像s=“2+3*5/7”,那么输出将是4,因为2+(((3*5)/7)=4
让我们看下面的实现以更好地理解-
例
from math import floor, trunc
class Solution:
def solve(self, s):
s = list(s[::-1])
def get_value():
sign = 1
if s and s[-1] == "-":
s.pop()
sign = -1
value = 0
while s and s[-1].isdigit():
value *= 10
value += int(s.pop())
return sign * value
def get_term():
term = get_value()
while s and s[-1] in "*/":
op = s.pop()
value = get_value()
if op == "*":
term *= value
else:
term = floor(1.0 * term / value)
return term
ans = get_term()
while s:
op, term = s.pop(), get_term()
if op == "+":
ans += term
else:
ans -= term
return ans
ob = Solution()s = "2+3*5/7"
print(ob.solve(s))输入值
"2+3*5/7"
输出结果
4
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短