私はこのようなリストを持っています:
a=[(("x",0.312),("e",0.0232),("f",0.245),("a",0.1322))]
そして今、私はそれを最大ヒープツリーに挿入したいのですが、各ノードには両方の値が必要です (例:("x",0.312))。両方の値を別々に取得できます。Max Heap の実装方法を知っています。挿入機能の扱い方について助けが必要です。より簡単であれば、二分木にすることができます。ありがとう
class Heap:
def __init__(self):
self.heap = list()
#return the size of the tree
def size(self):
return len(self.heap)
def isLeaf(self, index):
#returns true if the index refers to a leaf, false otherwise
return self.size() < 2 * index + 2
def parent(self, index):
#returns the parent of the node at index
return(index - 1) // 2
def leftChild(self, index):
#returns the index of the left child of a node
return 2 * index + 1
def rightChild(self, index):
#returns the index of the right child of a node
return 2 * index + 2
def add(self, value):
#add a given value to the heap
#append the value to the list
#shift the element into the correct position
self.heap.append(value)
index= self.size()-1
while self.parent(index) >=0 and self.heap[index] < self.heap[self.parent(index)]:
swap= self.heap[index]
self.heap[index]=self.heap[self.parent(index)]
self.heap[self.parent(index)]=swap
index = self.parent(index)