ভূমিকা
এক জেনেরিক ট্রি (Generic Tree) স্ট্রাকচার বানানো এবং তার সকল নোডের মান যোগ করা একটি রিকার্সিভ প্রোগ্রামিং সমস্যা। এই নিবন্ধে একটি ইন্টারঅ্যাক্টিভ মেনু-চালিত প্রোগ্রাম দেখানো হয়েছে যেখানে ব্যবহারকারী রুট নোড যোগ করতে পারে, চাইল্ড নোড যোগ করতে পারে, এবং সকল নোডের যোগফল বের করতে পারে।
উদাহরণ কোড
class Tree_structure:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add_values(self, node):
self.children.append(node)
def search_val(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search_val(key)
if temp is not None:
return temp
return None
def summation_nodes(self):
sum_val = self.key
for child in self.children:
sum_val += child.summation_nodes()
return sum_val
tree = None
print('Menu (no duplicate keys allowed)')
print('add at root')
print('add below ')
print('summation')
print('quit')
while True:
my_input = input('What would you like to do? ').split()
operation = my_input[0].strip().lower()
if operation == 'add':
data = int(my_input[1])
newNode = Tree_structure(data)
sub_op = my_input[2].strip().lower()
if sub_op == 'at':
tree = newNode
elif sub_op == 'below':
my_pos = my_input[3].strip().lower()
key = int(my_pos)
ref_node = None
if tree is not None:
ref_node = tree.search_val(key)
if ref_node is None:
print('No such key exists')
continue
ref_node.add_values(newNode)
elif operation == 'summation':
if tree is None:
print('The tree is empty')
else:
summation_val = tree.summation_nodes()
print('Sum of all the nodes is : {}'.format(summation_val))
elif operation == 'quit':
break
আউটপুট
Menu (no duplicate keys allowed) add at root add below summation quit What would you like to do? add 56 at root What would you like to do? add 45 below 56 What would you like to do? add 23 below 56 What would you like to do? summation Sum of all the nodes is : 124 What would you like to do?
ব্যাখ্যা
Tree_structureক্লাসেkey(নোড মান) এবংchildren(চাইল্ড নোড들의 লিস্ট) আছে।search_valরিকার্সিভলি নোড খুঁজে বের করে।summation_nodesরিকার্সিভলি বর্তমান নোডের মান + সব চাইল্ডের যোগফল রিটার্ন করে।মেনু-চালিত ইন্টারফেসে ব্যবহারকারী কমান্ড দিয়ে ট্রি বানায় এবং যোগফল বের করে।
দ্রষ্টব্য
মূল কোডে child.search(key) কল করা হয়েছে কিন্তু মেথড নাম search_val। সংশোধন করা হয়েছে।