假设我有一个布尔公式,它使用一组已知的标记,例如:
- 布尔运算符:
and
,or
,not
- 分组操作符:
(
,)
给定使用这些标记的布尔公式,例如:
F: (A or B) and not(A and C)
如何将此定义转换为集合操作符的Python表达式?
Fp = (x in A or x in B) and not(x in A and x in C)
有关此问题的背景,请参阅此主题和已接受的答案
查看文档中的设置操作。你可以这样做:
Fp = (A | B) - C
假设变量长度为一个字符:
s = "(A or B) and not(A and C)"
print re.sub("(?<![a-zA-Z])([A-Za-z])(?![A-Za-z])", "x in \1", s)
看起来基本上你要把x in
附加到任何不是你的令牌之一的东西上。它看起来像这样,可能是:
tokens = ['and', 'or', 'not']
grouping = ['(', ')']
def resub(match):
matchval = match.group(0)
if matchval in tokens:
return matchval
return 'x in %s'%matchval
s = "(A or B) and not(A and C)"
re.sub('w+', resub, s)
'(x in A or x in B) and not(x in A and x in C)'
它应该适用于被识别为单词的符号;如果你需要更具体的东西(即你的变量中有其他字符),你需要自己定义它,而不是使用w
…
这个函数将匹配任何Python标识符,将替换任何所需的目标变量,并且它都被包装起来便于使用:
import re
def subst_in(s, varname, keywords={'and', 'or', 'not'}):
repl = "{} in {{}}".format(varname)
def fn(match):
s = match.group(0)
return s if s in keywords else repl.format(s)
return re.sub("[a-z_][a-z0-9_]*", fn, s, flags=re.I)
f = "(A or B) and not(A and C)"
fp = subst_in(f, "x")
为
'(x in A or x in B) and not(x in A and x in C)'
Edit:尽管坦率地说它应该是
'x in B or (x in A and x not in C)'