Python Mathematical expression Parsing and Evaluation Library
Write a Python library for parsing and evaluating mathematical expressions.
The problem involves creating a library that can parse and evaluate "mathematical expressions". This requires implementing a parser to convert input strings into a structured format (like an Abstract Syntax Tree) and an evaluator to compute the results of the parsed expressions. The library should support common mathematical functions and operations, ensure secure evaluation, and handle errors gracefully. The goal is to provide a reliable tool for users to perform mathematical computations dynamically from input strings.
Sample Solution:
Python Code :
# Import the Abstract Syntax Tree (AST) module
import ast
# Import the math module for mathematical functions and constants
import math
# Define a class for evaluating mathematical expressions
class MathExpressionEvaluator:
def __init__(self):
pass
# Method to evaluate mathematical expressions
def evaluate(self, expression):
try:
# Parse the expression into an Abstract Syntax Tree (AST)
parsed_expression = ast.parse(expression, mode='eval')
# Define the allowed names (functions and constants) for evaluation
allowed_names = {
'sin': math.sin,
'cos': math.cos,
'tan': math.tan,
'log': math.log,
'sqrt': math.sqrt,
**vars(math) # Include all functions and constants from the math module
}
# Evaluate the AST using a custom namespace that includes the allowed names
result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names)
return result
except SyntaxError:
print("Invalid expression syntax.")
return None
except Exception as e:
print("Error:", e)
return None
# Example usage
if __name__ == "__main__":
evaluator = MathExpressionEvaluator()
# Evaluate mathematical expressions
print("Evaluation Results:")
print("10 + 12 * 4 =", evaluator.evaluate("10 + 12 * 4"))
print("(12 + 13) * 4 =", evaluator.evaluate("(12 + 13) * 4"))
print("sin(0.5) =", evaluator.evaluate("sin(0.5)"))
print("log(10) =", evaluator.evaluate("log(10)"))
Output:
Evaluation Results: 10 + 12 * 4 = 58 (12 + 13) * 4 = 100 sin(0.5) = 0.479425538604203 log(10) = 2.302585092994046
Explanation:
- Imports: The code imports the "ast" module for parsing expressions into Abstract Syntax Trees (ASTs) and the "math" module for mathematical functions and constants.
- MathExpressionEvaluator Class: This class provides a method "evaluate" for evaluating mathematical expressions. It initializes with an empty "init" method.
- evaluate Method:
It takes an expression as input and attempts to parse it into an AST using 'ast.parse'. - It defines a dictionary 'allowed_names' that includes mathematical functions like 'sin', 'cos', 'tan', 'log', 'sqrt', and all functions and constants from the "math" module.
- It evaluates the AST using 'eval' with a custom namespace that includes the allowed names. This ensures that only specified functions and constants can be used in the expression.
- It catches "SyntaxError" and other exceptions, printing error messages if encountered.
- Example usage:
It creates an instance of 'MathExpressionEvaluator'. - It evaluates several mathematical expressions using the "evaluate" method and prints the results.
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Python Bloom Filter implementation.
Next: Python Dynamic Configuration Manager with Runtime Reload.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/advanced/python-mathematical-expression-parser-and-evaluator.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics