📅  最后修改于: 2022-03-11 14:47:11.947000             🧑  作者: Mango
class MaxPriority():
def __init__(self):
self.heap = []
self.tempNumber = []
self.tempWord = []
self.counter = int(0)
self.maxsize = int(0)
self.size = int(0)
def root(self,index):
if index == 0:
return True
return False
def leaf(self,index):
if index >= self.size//2 and index <= self.size:
return True
return False
def getParent(self, index):
if self.root(index):
return None
return (index-1)//2
def leftChild(self,index):
if self.leaf(index):
return None
return (index*2)+1
def rightChild(self,index):
if self.leaf(index):
return None
elif (index*2)+2 >= self.size:
return None
return (index*2)+2
def swap(self,src,dest):
self.heap[src], self.heap[dest] = self.heap[dest], self.heap[src]
def heapifyUp(self):
temp = self.size-1
if self.size>1:
while(self.heap[self.getParent(temp)] < self.heap[temp]):
self.swap(temp,self.getParent(temp))
temp = self.getParent(temp)
if self.getParent(temp) == None:
break
def heapifyDown(self):
temp = 0
if self.size == 2:
if self.rightChild(temp) != None:
if self.heap[self.leftChild(temp)] > self.heap[self.rightChild(temp)]:
self.swap(temp,self.leftChild(temp))
temp = self.leftChild(temp)
else:
self.swap(temp,self.rightChild(temp))
temp = self.rightChild(temp)
else:
if self.heap[self.leftChild(temp)] > self.heap[temp]:
self.swap(temp,self.leftChild(temp))
elif self.size>=3:
while(self.heap[temp] < self.heap[self.leftChild(temp)] or self.heap[temp] < self.heap[self.rightChild(temp)]):
if self.heap[self.leftChild(temp)] > self.heap[self.rightChild(temp)]:
self.swap(temp,self.leftChild(temp))
temp = self.leftChild(temp)
else:
self.swap(temp,self.rightChild(temp))
temp = self.rightChild(temp)
if self.leftChild(temp) == None or self.rightChild(temp) == None:
break
def add(self,word,number):
self.tempWord.append(word)
self.tempNumber.append(number)
self.size+=1
if self.size > self.maxsize:
self.heap.append(number)
self.maxsize+=1
else:
self.heap[self.size-1] = number
self.heapifyUp()
def delete(self):
self.heap[0] = self.heap[self.size-1]
self.size-=1
self.heapifyDown()
def selesaikan(self):
if self.size == 0:
print("Priority is empty !!")
elif self.size == 1:
print("Only one priority !!")
else:
self.counter=self.size
print("\n== URUTAN PRIORITAS TUGAS TOTO BERDASARKAN MAX HEAP ==")
for x in range (0,self.size):
for i in range(0,1):
for j in range(0,self.counter):
if(str(self.heap[i]) == str(self.tempNumber[j])):
print("-> Prioritas " + str(x+1) + " = " + str(self.tempWord[j]))
self.delete()
def peek(self):
if self.size>0:
return self.heap[0]
return None
tugas = MaxPriority()
print("\n== MEMPRORITASKAN TUGAS TOTO BERDASARKAN MAX HEAP ==")
n_data = int(input("-> Masukkan banyak data yang akan disusun : "))
for i in range (0,n_data):
name= input("\n1) Nama tugas : ")
priorityy = int(input("2) Prioritas : "))
print("-> Data berhasil disimpan!!")
tugas.add(name,priorityy)
tugas.selesaikan()