def findKthLargestByStack(self, nums: List[int], k: int) -> int: """ 使用最大堆 """ from heap import HeapMin h = HeapMin([-i for i in nums]) for i in range(k): ret = h.pop() return -ret
def queueHeap(self): size = len(self.__queue)+1 first = Node('', -1) inf = Node('', float("inf")) self.__heap_queue = HeapMin(first, size, inf) for char in self.__queue: try: self.__heap_queue.insertNode(Node(char, self.__queue[char])) except CapacityError as e: print(e.expr.upper() + ":\n" + e.msg + "\n") sys.exit(0)
def prim(self): """Algoritmo de Prim para hallar el árbol de expansión mínimo.""" bosque = [] aristas = HeapMin() origen = self.inicio.obtener_elemento(0) adyac = 0 while (adyac < origen['aristas'].tamanio()): arista = origen['aristas'].obtener_elemento(adyac) aristas.arribo([origen['info'], arista['destino']], arista['peso']) adyac += 1 # print(bosque) # print(aristas.elementos) # print() while (len(bosque) // 2 < self.tamanio() and not aristas.vacio()): dato = aristas.atencion() if (len(bosque) == 0) or ( (self.busqueda_prim(bosque, dato[1][0]) is not None) ^ (self.busqueda_prim(bosque, dato[1][1]) is not None)): bosque.append(dato) pos_vertice = self.buscar_vertice(dato[1][1]) nuevo_vertice = self.inicio.obtener_elemento(pos_vertice) adyac = 0 while (adyac < nuevo_vertice['aristas'].tamanio()): arista = nuevo_vertice['aristas'].obtener_elemento(adyac) # print(arista) aristas.arribo([nuevo_vertice['info'], arista['destino']], arista['peso']) adyac += 1 # print(bosque) # print(aristas.elementos) # a = input() return bosque
def schargepmtn_nlogn(jobs_list): R = HeapMin() Q = HeapMax() i=0 for job in jobs_list: R.add(Cell(value=job.head[0], job=i)) i += 1 # S = np.zeros(len(jobs_list)) # momenty rozpoczęcia wykonywania zadań # C = np.zeros(len(jobs_list)) # momenty zakończenia wykonywania zadań Nn = list(range(len(jobs_list))) Ng = [] # order = [] # Algorymt t = 0 l = 0 Cmax = 0 while len(Nn) > 0 or len(Ng) > 0: while len(Nn) > 0 and R.min().value <= t: j = R.min(True).job Nn.remove(j) Ng.append(j) Q.add(Cell(value=jobs_list[j].tail[0], job=j)) if jobs_list[j].tail[0] > jobs_list[l].tail[0]: jobs_list[l].body[0] = t - jobs_list[j].head[0] t = jobs_list[j].head[0] if jobs_list[l].body[0] > 0: Ng.append(l) Q.add(Cell(value=jobs_list[l].tail[0], job=l)) if len(Ng) == 0: t = R.min().value else: j = Q.max(True).job Ng.remove(j) l = j t = t + jobs_list[j].body[0] Cmax = max(Cmax, t + jobs_list[j].tail[0]) return Cmax
def prim(self, inicio=0): bosque = [] aristas = HeapMin() origen = self.inicio.obtener_elemento(inicio) adyac = 0 while (adyac < origen['aristas'].tamanio()): arista = origen['aristas'].obtener_elemento(adyac) aristas.arribo([origen['info'], arista['destino']], arista['peso']) adyac += 1 while (len(bosque) // 2 < self.tamanio() and not aristas.vacio()): dato = aristas.atencion() if (len(bosque) == 0) or ( (self.busqueda_prim(bosque, dato[1][0]) is not None) ^ (self.busqueda_prim(bosque, dato[1][1]) is not None)): bosque.append(dato) pos_vertice = self.buscar_vertice(dato[1][1]) nuevo_vertice = self.inicio.obtener_elemento(pos_vertice) adyac = 0 while (adyac < nuevo_vertice['aristas'].tamanio()): arista = nuevo_vertice['aristas'].obtener_elemento(adyac) aristas.arribo([nuevo_vertice['info'], arista['destino']], arista['peso']) adyac += 1 return bosque
def dijkstra(self, ver_origen, ver_destino): """Algoritmo de Dijkstra para hallar el camino mas corto.""" no_visitados = HeapMin() camino = Pila() aux = 0 while (aux < self.tamanio()): vertice = self.inicio.obtener_elemento(ver_origen) vertice_aux = self.inicio.obtener_elemento(aux) vertice_aux['anterior'] = None if (vertice_aux['info'] == vertice['info']): no_visitados.arribo([vertice_aux['info'], None], 0) else: no_visitados.arribo([vertice_aux['info'], None], inf) aux += 1 while (not no_visitados.vacio()): dato = no_visitados.atencion() camino.apilar(dato) pos_aux = self.buscar_vertice(dato[1][0]) vertice_aux = self.inicio.obtener_elemento(pos_aux) aristas = 0 while (aristas < vertice_aux['aristas'].tamanio()): arista = vertice_aux['aristas'].obtener_elemento(aristas) pos_heap = no_visitados.busqueda(arista['destino']) if (pos_heap is not None and no_visitados.elementos[pos_heap][0] > dato[0] + arista['peso']): no_visitados.elementos[pos_heap][1][1] = dato[1][0] nuevo_peso = dato[0] + arista['peso'] no_visitados.cambiar_prioridad(pos_heap, nuevo_peso) aristas += 1 # print(no_visitados.elementos) return camino
class Huffman: __queue, __table = {}, {} __heap_queue = [] __text, __bintext = '', '' def __init__(self, filename): with open(filename, 'r') as f: for line in f: for char in line: if char in self.__queue: self.__queue[char] += 1 else: self.__queue[char] = 1 self.__text += line def printQueue(self): for char in self.__queue: print("%c:%d" %(char, self.__queue[char])) def queueHeap(self): size = len(self.__queue)+1 first = Node('', -1) inf = Node('', float("inf")) self.__heap_queue = HeapMin(first, size, inf) for char in self.__queue: try: self.__heap_queue.insertNode(Node(char, self.__queue[char])) except CapacityError as e: print(e.expr.upper() + ":\n" + e.msg + "\n") sys.exit(0) def printHeapQueue(self): self.__heap_queue.printHeap() def printAllNodes(self): root = self.__heap_queue.getNode(1) level = root.height(root)+1 root.printNode(root, level) def printSequenceNodes(self): root = self.__heap_queue.getNode(1) root.printNodeLine(root) def joinElements(self): while(self.__heap_queue.getSize() > 2): left = self.__heap_queue.extractMin() right = self.__heap_queue.extractMin() root = Node(left.char+right.char, left.freq+right.freq, left, right) self.__heap_queue.insertNode(root) def compress(self): root = self.__heap_queue.getNode(1) root.passTree(root) self.__table = root.getTable() def extract(self, filename=''): b, txt = '', '' inv_table = dict((value, key) for key, value in self.__table.items()) text = self.__bintext if(filename != ''): f = open(filename, 'rb') text = self.__convertStringToBin(f.read().decode('ascii')) f.close() for char in text: b += char if b in inv_table: txt += inv_table[b] b = '' return txt def saveFile(self, filename): f = open(filename, 'w+') b = '' for char in self.__text: b += self.__table[char] f.write(b) f.close() self.__bintext = b def saveFileBin(self, filename): f = open(filename, 'wb') b = '' for char in self.__text: b += self.__table[char] f.write(self.__convertBinToString(b).encode('ascii')) f.close() self.__bintext = b def __convertBinToString(self, b): start, end = 0, 7 text = '' while(end < len(b)+7): temp = b[start:end] text += chr(int(temp, 2)) start, end = end, end+7 return text def __convertStringToBin(self, b): i = 0 text = '' while(i < len(b)): temp = b[i] text += str(bin(ord(temp)))[2:].zfill(7) i += 1 return text def printTexts(self): print(self.__text) print(self.__bintext) def printTable(self): print(self.__table) def printSizes(self): sizeOriginalText = len(self.__text)*8 sizeCompressText = len(self.__bintext) compressRatio = 100-float((sizeCompressText*100)/sizeOriginalText) print("Tamanho do texto original em bits: %d" %(sizeOriginalText)) print("Tamanho do texto compactado em bits: %d" %(sizeCompressText)) print("Taxa de compactacao: %.2f%%" %compressRatio)
def schrange_nlogn(jobs_list): ''' Simulate RPQ problem :param jobs_list: :param order: :return: ''' R = HeapMin() Q = HeapMax() i=0 for job in jobs_list: R.add(Cell(value=job.head[0], job=i)) i += 1 S = np.zeros(len(jobs_list)) # momenty rozpoczęcia wykonywania zadań C = np.zeros(len(jobs_list)) # momenty zakończenia wykonywania zadań Nn = list(range(len(jobs_list))) Ng = [] order = [] # Algorymt t = R.min().value while len(Nn) > 0 or len(Ng) > 0: while len(Nn) > 0 and R.min().value <= t: j = R.min(True).job Nn.remove(j) Ng.append(j) Q.add(Cell(value=jobs_list[j].tail[0], job=j)) if len(Ng) == 0: t = R.min().value else: j = Q.max(True).job Ng.remove(j) order.append(j) t += jobs_list[j].body[0] # S czas rozpoczecia zadania first = True for i in order: if first: S[i] = jobs_list[i].head[0] i_last = i first = False else: S[i] = max(jobs_list[i].head[0], S[i_last]+jobs_list[i_last].body[0]) i_last = i # C czas zakonczenia zadania for i in order: C[i] = S[i] + jobs_list[i].body[0] # Obliczenie cmax cmax = [] for i in order: cmax.append(C[i]+jobs_list[i].tail[0]) # Najdłuższy czas jako ostatnie zakonczone zadania cmax = max(cmax) return order, cmax