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)