假设我有一个布尔公式,它使用一组已知的标记,例如:
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)
有关此问题的背景信息,请参阅此thread and accepted answer。
答案 0 :(得分:1)
请参阅set operations的文档。你可以这样做:
Fp = (A | B) - C
答案 1 :(得分:1)
假设您的变量长度为一个字符:
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)
答案 2 :(得分:1)
看起来基本上你会将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
......
答案 3 :(得分:1)
此函数将与任何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)'
编辑:虽然坦率地说应该是
'x in B or (x in A and x not in C)'