Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to evaluate one mathematical expression without built-in functions in python
Sometimes we need to evaluate mathematical expressions without using Python's built-in eval() function. This requires parsing the expression manually while respecting operator precedence rules.
So, if the input is like s = "2+3*5/7", then the output will be 4, as 2 + ((3 * 5) / 7) = 4.
Algorithm Overview
To solve this, we follow these steps ?
- Reverse the input string to process from right to left
- Create a
get_value()function to parse numbers and handle signs - Create a
get_term()function to handle multiplication and division (higher precedence) - In the main function, handle addition and subtraction (lower precedence)
Implementation
Let us see the following implementation to get better understanding ?
from math import floor
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
# Test the solution
ob = Solution()
s = "2+3*5/7"
print(f"Expression: {s}")
print(f"Result: {ob.solve(s)}")
The output of the above code is ?
Expression: 2+3*5/7 Result: 4
How It Works
The algorithm works by processing the expression in reverse order:
- get_value(): Extracts numbers and handles negative signs
- get_term(): Processes multiplication and division operations first (higher precedence)
- Main loop: Handles addition and subtraction operations last (lower precedence)
Step-by-Step Execution
For the expression "2+3*5/7":
- Reverse string:
"7/5*3+2" - First term:
2 - Operator:
+ - Second term:
3*5/7 = 15/7 = 2(integer division) - Final result:
2 + 2 = 4
Conclusion
This approach correctly evaluates mathematical expressions by respecting operator precedence without using built-in functions. The key insight is processing the expression in reverse order and handling multiplication/division before addition/subtraction.
