Open In App

Python – Evaluate Expression given in String

Sometimes, while working with Python Strings, we can have certain computations in string format and we need to formulate its result. This can occur in domains related to Mathematics and data. Let’s discuss certain ways in which we can perform this task.

Method #1 : Using regex + map() + sum() 



The combination of above functions can be used to solve this problem. In this, we perform the task of computation using sum() and mapping of operator and operation using map(). This method can be used if the string has only + or -. Method #2 can be used for other operations as well.




# Python3 code to demonstrate working of
# Expression evaluation in String
# Using regex + map() + sum()
import re
 
# initializing string
test_str = "45 + 98-10"
 
# printing original string
print("The original string is : " + test_str)
 
# Expression evaluation in String
# Using regex + map() + sum()
res = sum(map(int, re.findall(r'[+-]?\d+', test_str)))
 
# printing result
print("The evaluated result is : " + str(res))

Output : 

The original string is : 45+98-10
The evaluated result is : 133

 

Method #2 : Using eval() 
This is one of the way in which this task can be performed. In this, we perform computation internally using eval(). 




# Python3 code to demonstrate working of
# Expression evaluation in String
# Using eval()
 
# initializing string
test_str = "45 + 98-10"
 
# printing original string
print("The original string is : " + test_str)
 
# Expression evaluation in String
# Using eval()
res = eval(test_str)
 
# printing result
print("The evaluated result is : " + str(res))

Output : 
The original string is : 45+98-10
The evaluated result is : 133

 

Method #3: Using loop and stack

Step-by-step approach:




exp = "45+98-10"
stack = []
i = 0
while i < len(exp):
    if exp[i].isdigit():
        num = int(exp[i])
        i += 1
        while i < len(exp) and exp[i].isdigit():
            num = num * 10 + int(exp[i])
            i += 1
        stack.append(num)
    elif exp[i] == "+":
        stack.append("+")
        i += 1
    elif exp[i] == "-":
        stack.append("-")
        i += 1
    else:
        i += 1
 
result = stack[0]
for i in range(1, len(stack), 2):
    if stack[i] == "+":
        result += stack[i+1]
    else:
        result -= stack[i+1]
 
print("The evaluated result is:", result)

Output
The evaluated result is: 133

Time Complexity: O(n), where n is the length of the expression string. The while loop that extracts numbers from the string takes O(n) time, and the for loop that applies the operators takes O(n/2) time.
Space Complexity: O(n), as we are using a stack to store the digits and operators in the expression.

Method #4: Using regular expressions

Regular expressions can be used to extract numbers and operators from the expression string and then evaluate the expression using a loop

Step-by-step approach:




import re
 
def evaluate_expression(expression):
    # Extract numbers and operators from the expression string
    elements = re.findall(r'(\d+|\+|\-|\*|\/)', expression)
 
    # Initialize the result to the first number
    result = int(elements[0])
 
    # Apply each operator to the previous result and the current number
    for i in range(1, len(elements), 2):
        operator = elements[i]
        num = int(elements[i+1])
        if operator == '+':
            result += num
        elif operator == '-':
            result -= num
        elif operator == '*':
            result *= num
        elif operator == '/':
            result /= num
 
    return result
 
# Test the function
expression = "45+98-10"
print("The original string is:", expression)
print("The evaluated result is:", evaluate_expression(expression))

Output
The original string is: 45+98-10
The evaluated result is: 133

Time complexity: O(n), where n is the length of the expression string
Space complexity: O(n), where n is the length of the expression string

Method 5: Using reduce():
Algorithm:




# Python3 code to demonstrate working of
# Expression evaluation in String
# Using regex + reduce()
import re
from functools import reduce
 
# initializing string
test_str = "45 + 98-10"
 
# printing original string
print("The original string is : " + test_str)
 
# Expression evaluation in String
# Using regex + reduce()
res = reduce(lambda x, y: x+y, map(int, re.findall(r'[+-]?\d+', test_str)))
 
# printing result
print("The evaluated result is : " + str(res))
#This code is contributed by Pushpa.

Output
The original string is : 45 + 98-10
The evaluated result is : 133

Time complexity: O(n), where n is the length of the input string. This is because the string has to be traversed once to obtain the integer values using regex.
Space complexity: O(n), where n is the length of the input string. This is because the list of integer values obtained from the string using regex has to be stored in memory.

METHOD 6:Using AST module

APPROACH:

This approach uses the ast module to parse the input string into an abstract syntax tree (AST), which represents the expression in a structured form. The AST is then compiled into a code object using the compile() function, and finally evaluated using the eval() function.

ALGORITHM:

1. Initialize the input string.
2. Parse the input string into an abstract syntax tree (AST) using the ast.parse() function.
3. Compile the AST into a code object using the compile() function.
4. Evaluate the code object using the eval() function to obtain the result.
5. Print the input string and the evaluated result.




import ast
 
expr = '45+98-10'
node = ast.parse(expr, mode='eval')
result = eval(compile(node, '<string>', 'eval'))
print("The original string is :", expr)
print("The evaluated result is :", result)

Output
The original string is : 45+98-10
The evaluated result is : 133

Time complexity: The time complexity of this approach depends on the complexity of the input expression. In the worst case, the AST can have a complexity of O(n^2), where n is the length of the input string. The compile() function has a time complexity of O(1), and the eval() function has a time complexity that depends on the complexity of the code object.

Space complexity: The space complexity of this approach is O(n), where n is the length of the input string. This is because the AST and the code object both require memory proportional to the size of the input string.


Article Tags :