Python 程序来实现二项树


当需要用 Python 实现二项树时,会用到面向对象方法。此处,定义了一个类和属性。在该类中定义用于执行某些操作的函数。创建该类的实例,并使用该函数执行计算器操作。

以下是对此执行操作的演示演示:

示例

 实时演示

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))

输出

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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义名为“binomial_tree”的类。
  • 它有一个方法,用于将元素添加到树的末尾。
  • 创建空列表。
  • 根据选项,用户选择一个选项。
  • 如果选择创建键,将创建类的实例,并创建二项树。
  • 还可以计算索引、根值和顺序。
  • 如果需要合并索引,将选择另一个选项,并提及需要合并的节点的索引值。
  • 这会合并数据并显示数据。

更新于:2021 年 3 月 12 日

538 次浏览

开启您的职业之旅

完成课程获得认证

开始学习
广告