Mapytex/mapytex/calculus/random/expression.py

44 lines
1.3 KiB
Python

from ..API.expression import Expression
from .core.random_tree import RandomTree
DEFAUTL_CONFIG = {
"rejected": [0, 1],
"min_max": (-10, 10),
}
def expression_generator(
template: str,
conditions: list[str] = [],
global_config: dict = {},
configs: dict = {},
):
"""Generate a random expression
:param template: the template of the expression
:param conditions: conditions on randomly generate variable
:param global_config: configuration for all variables
:param configs: configuration for each variables
:return: Expression or Token generated
:example:
>>> e = expression_generator("{a}/{a*k}")
>>> e # doctest: +SKIP
<Exp: -3 / -15>
>>> e = expression_generator("{a}/{a*k} - 3*{b}", configs={'a':{'min_max':(10, 30)}})
>>> e # doctest: +SKIP
<Exp: 18 / 108 - 3 * 9>
>>> e = expression_generator("{a}*x + {b}*x + 3", conditions=["a>b"], global_config={"rejected":[0, 1]})
>>> print(e) # doctest: +SKIP
10x - 6x + 3
>>> ee = e.simplify()
>>> print(ee) # doctest: +SKIP
4x + 3
"""
rd_tree = RandomTree.from_str(template)
generated_tree = rd_tree.generate(
conditions, dict(DEFAUTL_CONFIG, **global_config), configs
)
return Expression._post_processing(generated_tree)