Reputation: 427
I have a logical expression like :
expression = '(1 & 2) & 3'
and a dictionary as, x = {1: '1', 2: '0', 3: '0'}
--- keys can be int or string, manageable
I need to evaluate this string as,
'(1 & 2) & 3'
=> '(x[1] & x[2]) & x[3]'
=> '(1 & 0) & 0'
=> eval('(1 & 0) & 0') = 0
I'm currently doing it like this:
re.sub('(\d+)', r'x[\1]', expression)
=> '(x[1] & x[2]) & x[3]'
but can't run eval on this
or
re.sub('(\d+)', eval(r'x[\1]'), expression)
=> eval(x[\1]) --> logical error
Please share an effective solution to achieve this. The application can define different expressions and one expression is used to evaluate 1000s of dictionaries like x.
Upvotes: 2
Views: 132
Reputation:
Incase it helps. without regex
def complement_n(expression):
expression_dict = {'1': '1','2': '0', '3': '0', '&':'&','(':'(',')':')',' ': ' '
#expression_dict = dict(a='t', c='g', t='a', g='c'),
}
comp_string = ''
for base in expression:
comp_string += expression_dict[base]
##comp_string += dna_complement.get(base, 'some_value')
return comp_string
expression = '(1 & 2 ) & 3'
comp_string = complement_n(expression)
print ("Complement is:", comp_string)
Upvotes: 0
Reputation: 88276
What you could do, is define a lambda
function as replacement, and lookup in the dictionary for each match:
import re
expression = '(1 & 2) & 3'
d = {1: '1', 2: '0', 3: '0'}
res = re.sub('(\d+)', lambda x: d[int(x.group(1))], expression)
#'(1 & 0) & 0'
eval(res)
# 0
If the expression could contain integers not present in the dictionary, you could adapt something like:
res = re.sub('(\d+)', lambda x: d.get(int(x.group(1)), '0'), expression)
Upvotes: 4