Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để triển khai cây nhị thức

Khi cần triển khai cây nhị thức trong Python, phương pháp hướng đối tượng được sử dụng. Ở đây, một lớp được định nghĩa và các thuộc tính được định nghĩa. Các hàm được định nghĩa trong lớp thực hiện các hoạt động nhất định. Một thể hiện của lớp được tạo và các hàm được sử dụng để thực hiện các phép tính trên máy tính.

Dưới đây là một minh chứng cho điều tương tự -

Ví dụ

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

Đầu ra

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

Giải thích

  • Một lớp có tên 'binomial_tree' được xác định.
  • Nó có một phương thức để thêm các phần tử vào cuối cây.
  • Một danh sách trống được tạo.
  • Dựa trên các tùy chọn, người dùng chọn một tùy chọn.
  • Nếu họ chọn tạo khóa, thì một phiên bản của lớp sẽ được tạo và cây nhị thức sẽ được tạo.
  • Chỉ số, giá trị gốc và thứ tự cũng được tính toán.
  • Nếu các chỉ số cần được kết hợp, một tùy chọn khác sẽ được chọn và giá trị chỉ số của các nút cần được kết hợp cũng được đề cập.
  • Điều này kết hợp dữ liệu và hiển thị nó.