【问题标题】:Understanding python code to implement logical expressions理解python代码实现逻辑表达式
【发布时间】:2017-06-12 20:38:52
【问题描述】:

我想在 python 中存储和工作(从表达式中访问每个文字,并进一步访问)像 ((A /\ B) / C) 这样的逻辑表达式。我找到了一种方法。我在下面发布代码。但作为一个初学者,我无法理解它。谁能向我解释这段代码是如何工作的并给出所需的输出。请原谅我第一次在 stackoverflow 上出现的任何错误。

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)

【问题讨论】:

    标签: python logic logical-operators


    【解决方案1】:

    通过设置类 Element 并定义位运算符 & 来工作 | ~ 返回您请求的操作的字符串表示形式。

    通常,~a 是对整数的按位运算:它将所有0 位更改为1,反之亦然。但是因为操作符__invert__已经被重新定义了,当你这样做的时候

    a = Element("A")
    print(~a)
    

    不是像使用整数那样得到a 的按位倒数,而是得到字符串"~A"

    它非常聪明,但我怀疑它对于你想做的事情不会很有用。它所做的只是将表达式转换为字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-03
      • 2016-07-28
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      相关资源
      最近更新 更多