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 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
(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) + (current.address[1] + 1)] or nextVertex == grid_list[ ((current.address[0] + 1) * 160) + (current.address[1] - 1)]: direction = "diagonally"
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
#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) print('Finished')
from BinaryHeap import BinaryHeap horarios = BinaryHeap(1000000) for x in range(1000000): horarios.insert(x, x) for x in range(1000000): horarios.extractMax()