Suppose we have a string that represents a mathematical expression with (+, -, *, /) Here / is representing integer division, we have to evaluate and return the result without using any built-in function.
So, if the input is like s = "2+3*5/7", then the output will be 4, as 2 + ((3 * 5) / 7) = 4
To solve this, we will follow these steps −
- s := reverse the given string
- Define a function get_value().
- sign := 1
- if s is not empty and last element of s is same as "-", then
- delete last element from s
- sign := -1
- value := 0
- while s is not empty and last element of s is a digit, do
- value := value * 10
- value := value + numeric value of last element from s, and delete last element of s
- return sign * value
- Define a function get_term()
- term := get_value()
- while s is not empty and last element of s is either * or /, do
- op := last element of s and delete last element from s
- value := get_value()
- if op is same as "*", then
- term := term * value
- otherwise,
- term := the floor of (1.0 * term / value)
- return term
- From the main method do the following:
- ans := get_term()
- while s is not empty, do
- op := last element of s, and delete it from s
- term := get_term()
- if op is same as "+", then
- ans := ans + term
- otherwise,
- ans := ans - term
- return ans
Let us see the following implementation to get better understanding −
Example
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))
Input
"2+3*5/7"
Output
4