将布尔公式映射到Python集表达式

2024-03-28 22:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个布尔公式,它使用一组已知的标记,例如:

  • 布尔运算符:andornot
  • 分组运算符:()

给定一个使用这些标记的布尔公式,例如:

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。你知道吗


Tags: orandin标记信息定义表达式not
3条回答

参见文档中的set operations。你可以这样做:

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。。。你知道吗

相关问题 更多 >