Mapytex/mapytex/calculus/random/core/grammar.py

44 lines
1.2 KiB
Python

import math
EVAL_FUN = {**math.__dict__}
def extract_letters(words: list[str]) -> set[str]:
"""Extracts unique letters from a list of words
:param words: list of leafs
:return: set of letters
:example:
>>> leafs = ["a", "a*k"]
>>> extract_letters(leafs) == {'a', 'k'}
True
"""
letters = set()
for word in words:
for c in word:
if c.isalpha():
letters.add(c)
return letters
def eval_words(words: list[str], values: dict[str, int]) -> dict[str, int]:
"""Evaluate words replacing letters with values
:param words: list of words
:param values: Dictionary of letters:value
:return: Dictionary of evaluated words from generated values
In words, you have access to all math module functions
:example:
>>> leafs = ["a", "a*k"]
>>> generated_values = {"a":2, "k":3}
>>> eval_words(leafs, generated_values)
{'a': 2, 'a*k': 6}
>>> leafs = ["exp(a)", "gcd(a, k)"]
>>> generated_values = {"a":2, "k":3}
>>> eval_words(leafs, generated_values)
{'exp(a)': 7.38905609893065, 'gcd(a, k)': 1}
"""
return {word: eval(word, EVAL_FUN, values) for word in words}