-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.py
45 lines (36 loc) · 1.34 KB
/
node.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
Abhay Kulkarni
python v3.9
Node class
"""
from leaf import Leaf
# Node class, has 2 children for storing either a (Node and/or Leaf)
class Node:
def __init__(self, attribute, attribute_name=None, default_child=None, child=None):
if child is None:
child = {}
self.attribute = attribute
self.attribute_name = attribute_name
self.default_child = default_child
self.child = child
def add(self, val, subtree):
self.child[val] = subtree
# For debugging by printing
def show_tree(self, indent=0):
name = self.attribute_name
print('Test', name)
for (key, value) in self.child.items():
print(((' ' * 2 * indent) + " If " + str(name) + ' is ' + str(key) + ' ==> '), end=' ')
if isinstance(value, Node):
value.show_tree(indent + 1)
elif isinstance(value, Leaf):
print(value.op())
# To test the model
def __call__(self, example):
attribute_value = example[self.attribute]
if attribute_value in self.child:
return self.child[attribute_value](example)
else:
return self.default_child(example)
def __repr__(self):
return "Branch (" + str(self.attribute_name) + " , " + str(self.child) + ")"