Python Program to Implement Binomial Tree


When it is required to implement a binomial tree in Python, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to perform calculator operations.

Below is a demonstration for the same −

Example

 Live Demo

class binomial_tree:
   def __init__(self, key):
      self.key = key
      self.children = []
      self.order = 0
   def add_at_end(self, t):
      self.children.append(t)
      self.order = self.order + 1
my_tree = []
print('Menu')
print('create <key>')
print('combine <index1> <index2>')
print('exit')
while True:
   option = input('What do you wish like to do? ').split()
   operation = option[0].strip().lower()
   if operation == 'create':
      key = int(option[1])
      b_tree = binomial_tree(key)
      my_tree.append(b_tree)
      print('Binomial tree has been created.')
   elif operation == 'combine':
      index_1 = int(option[1])
      index_2 = int(option[2])
      if my_tree[index_1].order == my_tree[index_2].order:
         my_tree[index_1].add_at_end(my_tree[index_2])
         del my_tree[index_2]
         print('Binomial trees have been combined.')
      else:
         print('Order of trees need to be the same to combine them.')
   elif operation == 'exit':
      print("Exit")
      break
   print('{:>8}{:>12}{:>8}'.format('Index', 'Root key', 'Order'))
   for index, t in enumerate(my_tree):
print('{:8d}{:12d}{:8d}'.format(index, t.key, t.order))

Output

Menu
create <key>
combine <index1> <index2>
exit
What do you wish like to do? create 7
Binomial tree has been created.
Index Root key Order
0 7 0
What do you wish like to do? create 11
Binomial tree has been created.
Index Root key Order
0 7 0
1 11 0
What do you wish like to do? create 4
Binomial tree has been created.
Index Root key Order
   0    7    0
   1    11    0
   2    4    0
What do you wish like to do? combine 0 1
Binomial trees have been combined.
Index Root key Order
   0    7    1
   1    4    0
What do you wish like to do? exit
Exit

Explanation

  • A class named ‘binomial_tree’ is defined.
  • It has a method to add elements to the end of the tree.
  • An empty list is created.
  • Based on the options, the user chooses an option.
  • If they choose to create a key, an instance of class is created, and a binomial tree is created.
  • The index, root value and the order are also computed.
  • If indices need to be combined, another option is chosen, and the index values of nodes that need to be combined is also mentioned.
  • This combines the data, and displays it.

Updated on: 12-Mar-2021

474 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements