파이썬에서 이항 트리를 구현해야 하는 경우 객체 지향 방식을 사용합니다. 여기에서 클래스가 정의되고 속성이 정의됩니다. 함수는 특정 작업을 수행하는 클래스 내에서 정의됩니다. 클래스의 인스턴스가 생성되고 함수는 계산기 작업을 수행하는 데 사용됩니다.
아래는 동일한 데모입니다 -
예
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
설명
- 'binomial_tree'라는 클래스가 정의되었습니다.
- 트리 끝에 요소를 추가하는 메소드가 있습니다.
- 빈 목록이 생성됩니다.
- 옵션에 따라 사용자가 옵션을 선택합니다.
- 키 생성을 선택하면 클래스 인스턴스가 생성되고 이항 트리가 생성됩니다.
- 인덱스, 루트 값 및 순서도 계산됩니다.
- 인덱스를 결합해야 하는 경우 다른 옵션을 선택하고 결합해야 하는 노드의 인덱스 값도 함께 언급합니다.
- 데이터를 결합하여 표시합니다.