无需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 生日广州男生祝福语简短