Open In App

Python – Evaluate Expression given in String

Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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




# 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:

  • Take input of the string containing the expression to be evaluated
  • Initialize an empty stack
  • Loop through each character in the string:
  • If the character is a digit, extract the entire number and push it onto the stack
  • If the character is an operator, push it onto the stack
  • While the stack has more than one element:
  • Pop the top two elements from the stack
  • If the top element is an operator, apply it to the two popped elements and push the result onto the stack
  • Otherwise, push the popped elements back onto the stack in the reverse order
  • The final element left on the stack will be the evaluated result
  • Display the result

Python3




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 the re module for regular expressions
  • Use re.findall() to extract all the numbers and operators from the expression string and store them in a list
  • Use a loop to iterate through the list and evaluate the expression by applying each operator to the previous result and the current number
  • Return the final result

Python3




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:

  • Import the required modules: re and reduce.
  • Initialize the string to be evaluated.
  • Print the original string.
  • Use reduce() method to sum up the integer values obtained from the string using regex.
  • Print the result obtained from reduce().

Python3




# 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.

Python3




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.



Last Updated : 07 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads