def test_min(): n = 500 rs = [random() for _ in range(n)] P = BinaryHeap(lambda x, y: x <= y) for r in rs: P.insert(r) ss = [P.extract() for _ in range(n)] sortedr = sorted(rs) assert all([sortedr[i] == ss[i] for i in range(n)])
def test_max(): n = 500 rs = [random() for _ in range(n)] P = BinaryHeap(lambda x, y: x >= y) for r in rs: P.insert(r) ss = [P.extract() for _ in range(n)] rs.sort() rs.reverse() assert all([rs[i] == ss[i] for i in range(n)])
def heap_sort(a): """ Sorts a list using a binary heap. """ # Create the binary heap heap = BinaryHeap(a) # Build the sorted list for i in range(len(a)): a[i] = heap.get()
def main(): length = 10 binHeap = BinaryHeap(length) binHeap.print_heap() binHeap.heap_sort() if binHeap.is_sorted(): print("Successful Sort.") binHeap.print_heap()
def HeapSort(A): ''' Continuely call ExtractMax, which always return the root of heap ''' h = BinaryHeap(A.copy()) h.Heapify() for i in reversed(range(len(A))): A[i] = h.ExtractMax() return A
def dijkstra(self, id_start_node, min_departure_time): """ :param id_start_node: stazione di partenza :param min_departure_time: orario minimo in cui si è disposti a partire """ distances = [] #array delle distanze dal nodo sorgente heap = BinaryHeap() #inizializzo una heap binaria previous_nodes = [] #inizializzo la lista dei nodi già visitati timetables = [ ] #inizializzo la lista degli orari di arrivo per ciascun nodo time_departures = [ ] #inizializzo la lista degli orari di partenza per ciascun nodo run_id_list = [] #inizializzo la lista delle corse per ciascun nodo line_id_list = [] #inizializzo la lista delle linee per ciascun nodo for i, x in enumerate(self.nodes_list): distances.append(sys.maxsize) #inizializzo diversi valori previous_nodes.append(-1) timetables.append("-1") run_id_list.append("-1") line_id_list.append("-1") time_departures.append("-1") heap.add( x.id, distances[self.id_to_number[x.id]] ) #aggiungo alla heap l'id della stazione e la distanza fra il nodo e la sorgente distances[self.id_to_number[ id_start_node]] = 0 #pongo a 0 la distanza fra lo start_node e la sorgente timetables[self.id_to_number[ id_start_node]] = min_departure_time #aggiorno l'orario di arrivo nel nodo sorgente al minimo orario di partenza heap.decreaseKey( id_start_node, 0 ) #decremento il valore della heap ad indice idToNumber[startNodeId] a 0 in modo da essere la sorgente while len(heap.list_vertices) > 0: #finchè la heap non è vuota u = heap.extractMin() #estraggo il minimo if timetables[self.id_to_number[u.id]] != "-1": for edge in self.nodes_list[self.id_to_number[u.id]].adj_arr: # poichè la partenza da una stazione deve essere dopo l'orario di arrivo nella stazione precedente if distances[self.id_to_number[u.id]] + ( self.attendanceTime( timetables[self.id_to_number[u.id]], edge.departure_time) + (self.time(edge.arrival_time) - self.time(edge.departure_time))) < distances[ self.id_to_number[edge.id_arrival_station]]: distances, previous_nodes, timetables, run_id_list, line_id_list, time_departures = self.relax( self.id_to_number[u.id], self.id_to_number[edge.id_arrival_station], previous_nodes, distances, edge, timetables, run_id_list, line_id_list, time_departures) heap.decreaseKey( edge.id_arrival_station, distances[ self.id_to_number[edge.id_arrival_station]]) return distances, previous_nodes, timetables, run_id_list, line_id_list, time_departures
def Dijkstra(self): """ Returns the path from the start position to the goal position using Dijkstra's algorithm (DA). Returns <None> if no solution is found. """ # Initialize the binary heap bh = BinaryHeap(heap_type='min') # Add the start point to the binary heap. g = 0 bh.put((g, self.start)) g_values = {self.start: g} previous = {self.start: None} self.added = 1 # Loop until the priority queue is empty self.visited = 0 while (not bh.is_empty()): # Get the highest priority position from the priority queue (g, current) = bh.get() self.visited += 1 # Stop if it is the goal and return the path if (current == self.goal): path = self.get_path(previous) return path # Define the order in the directions idx = self.order_dir() # Add to the binary heap the neighbours of the current position for direction in idx: # Offset values row_offset, col_offset = self.offset[direction] # Neighbour position row_neigh = current[0] + row_offset col_neigh = current[1] + col_offset neighbour = (row_neigh, col_neigh) # If neighbour position is valid and not in the dictionary if (self.layout[row_neigh][col_neigh] != '#' and self.layout[row_neigh][col_neigh] != '*' and neighbour not in previous): # Values (the g-value of all neighbour positions differ # from the g-value of the current position by 1) g = g_values[current] + 1 # Add it to the priority queue bh.put((g, neighbour)) g_values[neighbour] = g previous[neighbour] = current self.added += 1 return None
def __init__(self, network, use_heap=False): self.use_heap = use_heap self.node_count = len(network.nodes) # Add each node in graph to Priority Queue if not use_heap: # Create an array for the queue self.queue = {} # For each node in the network for i in range(self.node_count): # Add the node to the array self.queue[network.nodes[i].node_id] = {'dist': math.inf} else: # Create a binary heap self.queue = BinaryHeap() # Add each element of the network to the queue for i in range(self.node_count): self.queue.insert(network.nodes[i].node_id, math.inf)
def repeated_backward_lazy(start_cell, goal_cell): solution = [start_cell] while solution[-1].x != solution[-1].x or solution[-1].y != goal_cell.y: path = compute_path(BinaryHeap(), goal_cell, solution[-1], "backward") if path != -1: solution.append(Cell(path[-2].x, path[-2].y, 0)) else: return -1 return solution
def repeated_backward_optimized(start_cell, goal_cell): end_node = start_cell while end_node.x != goal_cell.x or end_node.y != goal_cell.y: path = compute_path(BinaryHeap(), end_node, goal_cell, "backward") if path != -1: for node in path: if int(maze[node.x][node.y]) == 1: break update_agent_vision(node) end_node = node else: return -1 return backtrace(end_node)
def sumarListas(listas): resultado = [{'horario': horarioVacio(), 'grupo': [], 'codigo': [], 'asignatura': [], 'C_H': 0} for x in range(len(listas))] horarios = BinaryHeap(len(listas)) for i in range(len(resultado)): sirve = True for j in range(len(listas[i])): resultado[i]['C_H'] += listas[i][j]['C_G']*listas[i][j]['C_M'] for z in range(len(resultado[i]['horario'])): if resultado[i]['horario'][z] + listas[i][j]['horario'][z] < 2: resultado[i]['horario'][z] += listas[i][j]['horario'][z] else: sirve = False break if not sirve: break resultado[i]['grupo'].append(listas[i][j]['grupo']) resultado[i]['asignatura'].append(listas[i][j]['asignatura']) resultado[i]['codigo'].append(listas[i][j]['codigo']) if sirve: horarios.insert(resultado[i]['C_H'], {'asignaturas': resultado[i]['asignatura'], 'codigos': resultado[i]['codigo'], 'grupos': resultado[i]['grupo']}) return horarios
def sumarListas(listas): resultado = [] for x in range(len(listas)): lista_borrable = [0 for a in range(37)] lista_borrable[hash('horario')] = horarioVacio() lista_borrable[hash('grupo')] = [] lista_borrable[hash('codigo')] = [] lista_borrable[hash('asignatura')] = [] lista_borrable[hash('C_H')] = 0 resultado.append(lista_borrable) horarios = BinaryHeap(len(listas)) for i in range(len(resultado)): sirve = True for j in range(len(listas[i])): resultado[i][hash('C_H')] += listas[i][j][hash( 'C_G')] * listas[i][j][hash('C__m')] for z in range(len(resultado[i][hash('horario')])): if resultado[i][hash('horario')][z] + listas[i][j][hash( 'horario')][z] < 2: resultado[i][hash('horario')][z] += listas[i][j][hash( 'horario')][z] else: sirve = False break if not sirve: break resultado[i][hash('grupo')].append(listas[i][j][hash('grupo')]) resultado[i][hash('asignatura')].append( listas[i][j][hash('asignatura')]) resultado[i][hash('codigo')].append(listas[i][j][hash('codigo')]) if sirve: l = [0 for a in range(37)] l[hash('asignaturas')] = resultado[i][hash('asignatura')] l[hash('codigos')] = resultado[i][hash('codigo')] l[hash('grupos')] = resultado[i][hash('grupo')] horarios.insert(resultado[i][hash('C_H')], l) return horarios
def repeated_adaptive(start_cell, goal_cell): end_node = start_cell expanded = [[None for x in range(len(maze[0]))] for y in range(len(maze))] path_cost = sys.maxsize while end_node.x != goal_cell.x or end_node.y != goal_cell.y: (path, expanded) = compute_path_adaptive(BinaryHeap(), end_node, goal_cell, expanded, path_cost) if path != -1: path_cost = path[-1].g for node in path: if int(maze[node.x][node.y]) == 1: break update_agent_vision(node) end_node = node else: return -1 return backtrace(end_node)
#!/usr/bin/env python3 #Authors: M269 Module Team #Date: 19/1/13 from BinaryHeap import BinaryHeap #List from Miller and Ranum Figure 6.18. #Example 1 - adding items one at a time myHeap = BinaryHeap() aList = [9, 6, 5, 2, 3] print('Example 1 - adding items one at a time') print('List to build heap from:', aList) print('Heap list:', myHeap.heapList) print('-----------------------------------------') for k in range(len(aList)): myHeap.insert(aList[k]) print('-----------------------------------------') print('Finished: heap is', myHeap.heapList) print() #Example 2 - "heapifying" an existing list myHeap2 = BinaryHeap() bList = [9, 6, 5, 2, 3] print('Example 2 - heapifying an existing list') print('List to heapify:', bList) myHeap2.buildHeap(bList)
def findKthLargest(nums, k): heap = BinaryHeap() heap.build_heap(nums) for _ in range(len(nums) - k + 1): output = heap.extract_min() return output
from BinaryHeap import BinaryHeap horarios = BinaryHeap(1000000) for x in range(1000000): horarios.insert(x, x) for x in range(1000000): horarios.extractMax()
class PriorityQueue: """ Implement a priority queue that either uses an array or a heap 𝑔𝑒𝑡𝑛𝑒𝑥𝑡: Gets the next item with the smallest key Runs 𝑉 times • 𝑢𝑝𝑑𝑎𝑡𝑒𝑘𝑒𝑦 (and 𝑖𝑛𝑠𝑒𝑟𝑡): Updates the key of a desired vertex • Runs 𝑉 + 𝐸 times """ def __init__(self, network, use_heap=False): self.use_heap = use_heap self.node_count = len(network.nodes) # Add each node in graph to Priority Queue if not use_heap: # Create an array for the queue self.queue = {} # For each node in the network for i in range(self.node_count): # Add the node to the array self.queue[network.nodes[i].node_id] = {'dist': math.inf} else: # Create a binary heap self.queue = BinaryHeap() # Add each element of the network to the queue for i in range(self.node_count): self.queue.insert(network.nodes[i].node_id, math.inf) def get_next(self): # Pop the highest priority element off the queue if not self.use_heap: # Pop the smallest distance item of the array # O(n) because we need to iterate through each element in the array smallest_distance = math.inf # Initialize to infinity smallest_key = -1 # For each element in the queue for k, v in self.queue.items(): if self.queue[k]['dist'] < smallest_distance: smallest_distance = self.queue[k]['dist'] smallest_key = k smallest_node = {'id': smallest_key, 'dist': smallest_distance} if smallest_key == -1: popped_item = self.queue.popitem() return {'id': popped_item[0], 'dist': popped_item[1]['dist']} # Remove the element from queue del self.queue[smallest_key] # Delete in constant time # Return the smallest distance node return smallest_node else: # Return the root of return self.queue.delete_min() def update_key(self, node_id, dist): # Update the distance of a specified vertex if not self.use_heap: # Constant time O(1) self.queue[node_id]['dist'] = dist else: self.queue.update(node_id, dist) def is_empty(self): # Return True if the queue is empty # Return False if the queue is not empty if not self.use_heap: if len(self.queue) == 0: return True else: return False else: if self.queue.length() == 0: return True else: return False
def test_MaxHeap(): """ 25 / \ 15 20 / \ 13 14 """ emptyMinHeap = BinaryHeap(minHeapMode=False) with pytest.raises(IllegalStateException) as e_info: emptyMinHeap.peek() assert str(e_info.value) == 'The size of the heap is zero.' minHeap1 = BinaryHeap([25, 15, 20, 13, 14], minHeapMode=False) assert minHeap1.poll() == 25 assert minHeap1.peek() == 20 minHeap1.add(22) assert minHeap1.peek() == 22
def test_MinHeap(): """ 10 / \ 15 20 / \ 17 25 """ emptyMinHeap = BinaryHeap() with pytest.raises(IllegalStateException) as e_info: emptyMinHeap.peek() assert str(e_info.value) == 'The size of the heap is zero.' minHeap1 = BinaryHeap([10, 15, 20, 17, 25]) assert minHeap1.poll() == 10 assert minHeap1.peek() == 15 minHeap1.add(3) assert minHeap1.peek() == 3
for x in range(120): for y in range(160): if grid_list[(x * 160 + y)].status != "s" and grid_list[ (x * 160 + y)].status != "g": grid_list[(x * 160 + y)].distance = math.sqrt((x - start_x)**2 + (y - start_y)**2) start = getStart(grid_list) #calculate_distances(grid_list) start.distance = 0 #self.start.address[0] goal = getGoal(grid_list) fringe = BinaryHeap() closed = [] fringeList = [] path = [] fringe.insert(start, (start.distance + get_heuristic(start))) fringeList.append(start) def update_vertex(current, nextVertex): direction = "" if nextVertex == grid_list[ ((current.address[0] - 1) * 160) + (current.address[1] + 1)] or nextVertex == grid_list[ ((current.address[0] - 1) * 160) + (current.address[1] - 1)] or nextVertex == grid_list[ ((current.address[0] + 1) * 160) +
#!/usr/bin/env python3 #Authors: M269 Module Team #Date: 20/1/13 #Modified: 16/12/15 from BinaryHeap import BinaryHeap #Example 1 heapsort in action aList = [1, 9, 5, 2, 14, 4, 8, 20, 7, 42] #First 'heapify' the list myHeap = BinaryHeap() myHeap.buildHeap(aList) #Create empty list to hold the results sortedList = [] print('The list to be sorted:', aList) print('The heap:', myHeap.heapList) print() #While there are still items in the heap, pop the root and then reform the heap while myHeap.size() > 0: item = myHeap.delMin() sortedList.append(item) print('Finished') print('Sorted list:', sortedList)