2021-10-09 14:09:09 +00:00
|
|
|
import math
|
|
|
|
|
|
|
|
EVAL_FUN = {**math.__dict__}
|
|
|
|
|
2021-10-09 04:30:38 +00:00
|
|
|
def extract_letters(words: list[str]) -> set[str]:
|
|
|
|
"""Extracts unique letters from a list of words
|
2021-10-03 13:41:54 +00:00
|
|
|
|
|
|
|
: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
|
|
|
|
|
|
|
|
|
2021-10-09 04:30:38 +00:00
|
|
|
def eval_words(words: list[str], values: dict[str, int]) -> dict[str, int]:
|
|
|
|
"""Evaluate words replacing letters with values
|
2021-10-03 13:41:54 +00:00
|
|
|
|
|
|
|
:param words: list of words
|
|
|
|
:param values: Dictionary of letters:value
|
|
|
|
:return: Dictionary of evaluated words from generated values
|
|
|
|
|
2021-10-09 14:09:09 +00:00
|
|
|
In words, you have access to all math module functions
|
|
|
|
|
2021-10-03 13:41:54 +00:00
|
|
|
:example:
|
|
|
|
>>> leafs = ["a", "a*k"]
|
|
|
|
>>> generated_values = {"a":2, "k":3}
|
|
|
|
>>> eval_words(leafs, generated_values)
|
|
|
|
{'a': 2, 'a*k': 6}
|
2021-10-09 14:09:09 +00:00
|
|
|
>>> 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}
|
2021-10-03 13:41:54 +00:00
|
|
|
"""
|
2021-10-09 14:09:09 +00:00
|
|
|
return {word: eval(word, EVAL_FUN, values) for word in words}
|