1

I want to store and work (access each literal from an expression and further) on logical expressions like ((A /\ B) / C) in python. I found a way to do it. I am posting the code below. But as a beginner I'm unable to understand it. Can anyone explain to me how this code is working and giving the desired output. Forgive me for any mistakes as this my first time on 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)

1 Answer 1

1

It works by setting up the class Element and defining the bitwise operators & | ~ to return a string representation of the operation you asked for.

Normally, ~a is a bitwise operation on an integer: it changes all 0 bits to 1 and vice versa. But because the operator __invert__ has been redefined, when you do this

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

instead of getting the bitwise inverse of a as you would with an integer, you get the string "~A".

It's very clever, but I suspect it is not going to be very useful for what you want to do. All it does is turn an expression into a string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.