简体   繁体   English

如何在Python中处理逻辑表达式?

[英]How do I deal with a logical expression in Python?

let's say I got a logical expression in the format of ie. 假设我得到了ie格式的逻辑表达式。 AvBv~C->D . AvBv~C->D It consists of boolean elements and operators like (v,~,->) (disjunction,negation,implication). 它由布尔元素和运算符组成,如(v,~,->) (disjunction,negation,implication)。 I need to store those expressions and each element they consist of. 我需要存储这些表达式及其包含的每个元素。 Also each element should have a description so I guess I will have to make a class that will represent them (with fields representation and description ie. element1.representation="A" and element1.description="This is element A" but I am not sure whether this is the pythonic way, maybe a 2D array with names and descriptions as columns would be a better idea since the names are all unique. 此外,每个元素都应该有一个描述,所以我想我必须创建一个代表它们的类(带有字段representationdescriptionelement1.representation="A"element1.description="This is element A"但我是不确定这是否是pythonic方式,也许一个名称和描述为列的2D数组将是一个更好的主意,因为名称都是唯一的。

  1. Which data structure should I use to store such an expression? 我应该使用哪种数据结构来存储这样的表达式? Note the fact I need to store elements and operators which are of different type and then be able to restore them as logical expressions and do operations on them. 请注意,我需要存储不同类型的元素和运算符,然后能够将它们还原为逻辑表达式并对它们执行操作。
  2. Should I create methods for recognition of each element and operator to deal with the logical operations or is there a better approach? 我应该创建识别每个元素和运算符的方法来处理逻辑运算还是有更好的方法? Maybe use a parser like Lex-Yacc or some other library that deals with those? 也许使用像Lex-Yacc这样的解析器或其他一些处理这些的解析器?

Forgive me if I am not too clear but I'm coming from Java where I can't store different types of elements in the same data structure. 请原谅我,如果我不太清楚,但我来自Java,我无法在同一数据结构中存储不同类型的元素。

  1. Create a tree data structure that represents each element in the expression. 创建表示表达式中每个元素的树数据结构。
  2. You can indeed use a parser generator to produce the above data structures from a given string. 您确实可以使用解析器生成器从给定的字符串生成上述数据结构。

For example, a conjunction can be represented as follows and a similar approach can be used for variables: 例如,连接可以表示如下,类似的方法可以用于变量:

class Node:
    operator = "AND"
    left_node = None
    right_node = None
    description = "text"
    value = None

class Node:
    operator = "VAR"
    left_node = None
    right_node = None
    description = "text"
    value = "B"

You can then compose a tree out of these nodes. 然后,您可以从这些节点中组合树。

For example: A^B can be represented as a Node with AND where the left_node is a VAR node ( value=A ) and the right_node is a VAR node as well ( value=B ). 例如: A^B可以表示为具有ANDNode AND其中left_nodeVAR节点( value=A ),而right_node也是VAR节点( value=B )。

By declaring the __and__ , __or__ , and __invert__ methods, you can use the & , | 通过声明__and____or____invert__方法,你可以用&| and ~ operators to define your expressions. ~运算符来定义表达式。

class Element(object):
    def __init__(self, elt_id, elt_description=None):
        self.id = elt_id
        self.description = elt_description
        if self.description is None:
            self.description = self.id

    def __or__(self, elt):
        return CombinedElement(self, elt, op="OR")

    def __and__(self, elt):
        return CombinedElement(self, elt, op="AND")

    def __invert__(self):
        return CombinedElement(self, op="NOT")

    def __str__(self):
        return self.id

class CombinedElement(Element):
    def __init__(self, elt1, elt2=None, op="NOT"):
        # ID1
        id1 = elt1.id
        if isinstance(elt1, CombinedElement):
            id1 = '('+id1+')'
        # ID2
        if elt2 is not None:
            id2 = elt2.id
            if isinstance(elt2, CombinedElement):
                id2 = '('+id2+')'
        # ELT_ID
        if op == "NOT" and elt2 is None:
            elt_id = "~"+id1
        elif op == "OR": 
            elt_id = id1+" v "+id2
        elif op == "AND":
            elt_id = id1+" ^ "+id2
        # SUPER
        super(CombinedElement, self).__init__(elt_id)

a = Element("A")
b = Element("B")
c = Element("C")
d = Element("D")
e = Element("E")

print(a&b|~(c&d)|~e)

Output : 输出:

((A ^ B) v (~(C ^ D))) v (~E)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM