扁平化表达式算法



我找不到任何好的算法来压平dict中给定的值。我的表达式是一个带有"variables"的字符串。每个变量可以是一个数字或另一个变量,即:我的字典是

map = {
    'a': 4,
    'b': 6,
    'c': 'a+b',
    'd': 'c+a+4'
}

表达式可以是这样的:

first = 'a + b' # result should be: '4 + 6'

secound = 'd PLUS c' # result '4+6+4+4 PLUS 4+6'

我不想评估这个结果。我想知道如何用实数(来自map dict)替换(压平?)这样的变量

使用正则表达式替换(re.subRegexpObject.sub不仅接受替换字符串,还接受替换函数作为第二个参数):

import re
def flatten(expression, mapping):
    pattern = re.compile('|'.join(map(re.escape, mapping)))
    while pattern.search(expression):
        expression = pattern.sub(lambda m: mapping[m.group()], expression)
    return expression
mapping = {
    'a': 4,
    'b': 6,
    'c': 'a+b',
    'd': 'c+a+4'
}
# Convert all values to strings.
mapping = {key: str(mapping[key]) for key in mapping}

用法:

>>> flatten('a + b', mapping)
'4 + 6'
>>> flatten('d PLUS c', mapping)
'4+6+4+4 PLUS 4+6'

顺便说一句,不要使用map作为变量名。它将隐藏内置函数map

最新更新