sympy_utils
prairielearn.sympy_utils ¶
Utility functions for parsing and evaluating SymPy expressions.
convert_string_to_sympy ¶
convert_string_to_sympy(
expr: str,
variables: Iterable[str] | None = None,
*,
allow_hidden: bool = False,
allow_complex: bool = False,
allow_trig_functions: bool = True,
custom_functions: Iterable[str] | None = None,
assumptions: AssumptionsDictT | None = None,
) -> Expr
Convert a string to a sympy expression, with optional restrictions on the variables and functions that can be used. If the string is invalid, raise an exception with a message that can be displayed to the user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
expr
|
str
|
The string to convert to a sympy expression. |
required |
variables
|
Iterable[str] | None
|
A list of variable names that are allowed in the expression. |
None
|
allow_hidden
|
bool
|
Whether to allow hidden variables (like pi and e). |
False
|
allow_complex
|
bool
|
Whether to allow complex numbers (like i). |
False
|
allow_trig_functions
|
bool
|
Whether to allow trigonometric functions. |
True
|
custom_functions
|
Iterable[str] | None
|
A list of custom function names that are allowed in the expression. |
None
|
assumptions
|
AssumptionsDictT | None
|
A dictionary of assumptions for variables in the expression. |
None
|
Examples:
>>> convert_string_to_sympy("n * sin(7*m) + m**2 * cos(6*n)", variables=["m", "n"])
n * sympy.sin(m * 7) + m * m * sympy.cos(n * 6)
>>> convert_string_to_sympy("-infty")
-sympy.oo
>>> convert_string_to_sympy("z**2 + y - x", variables=["x", "y", "z"], allow_complex=True, assumptions={"x": {"positive": False}, "z": {"complex": True}})