简体   繁体   中英

Implement and/or tree in python

I need to implement an And/or tree in python so I can evaluate boolean expressions, I had an idea of creating a class that contains andNode , orNode and leafNode . The first two are are internal nodes that must have and or or values, the leafNode must have and integer value and represent the final leaves of the tree.I tried this but it doesn't seem to work:

class Node:
   def __init__(self,leaf):
     self.orNode = None
     self.andNode = None
     self.leaf = leaf

class and_or_tree (Node):
   def __init__(self):
       self.root=None

I need to test if an element exists in the tree, the height and iterate through it.

I think an example of such Leaf and and/or nodes could be something like this:

class Leaf: 
    def __init__(self, v):
        self.val = v;   

    def __call__(self): 
        return self.val 


class AndNode:
    def __init__(self, l, r):
        self.left = l; 
        self.right = r; 

    def __call__(self): 
        return self.left() and self.right() 



class OrNode: 
    def __init__(self, l, r):
        self.left = l; 
        self.right = r; 

    def __call__(self): 
        return self.left() or self.right()  

You can build a tree like this:

print AndNode(Leaf(True), Leaf(False))()  
print AndNode(OrNode(Leaf(True), Leaf(False)), Leaf(True))()  

Which outputs this:

False
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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