def median(array): med = [array.pop(0)] # h_high[0] has the minimum values of the highest values h_high = h.Heap(list()) # h_low[0] has the maximum value of the lowest values h_low = h.Heap(list(), True) h_low.insert(med[0]) for i in array: # trying to keep both Heaps balanced if i < h_low[0]: h_low.insert(i) else: h_high.insert(i) if h_low.__sizeof__() > h_high.__sizeof__() + 1: h_high.insert(h_low.extract()) elif h_low.__sizeof__() + 1 < h_high.__sizeof__(): h_low.insert(h_high.extract()) if h_low.__sizeof__() >= h_high.__sizeof__(): med.append(h_low[0]) else: med.append(h_high[0]) return med
def test_insert(self): binary_heap = heap.Heap() binary_heap.insert(3) self.assertEqual(binary_heap.heap, [-1, 3]) binary_heap = heap.Heap([-1, 20, 10, 16, 8, 7, 13, 14, 2, 5, 6]) binary_heap.insert(15) self.assertEqual(binary_heap.heap, [-1, 20, 15, 16, 8, 10, 13, 14, 2, 5, 6, 7])
def clustering_util(graph, initial_threshold, step_size): flag = True threshold = initial_threshold data = heap.Heap(lambda a, b: (a.ratio < b.ratio), False) initial = None final = None while flag: graph_aux = copy.deepcopy(graph) removed_edges = [] flag = False for i in range(graph_aux.size): vertex = graph_aux.get_vertex_by_index(i) j = 0 edge_len = len(vertex.edge_list) while j < edge_len: if vertex.edge_list[j].weight > threshold: flag = True removed_edges.append(vertex.edge_list[j]) graph_aux.erase_edge(vertex.edge_list[j].source_vertex, vertex.edge_list[j].target_vertex) j -= 1 edge_len = len(vertex.edge_list) j += 1 if flag: final = Data(threshold, validity_index(graph_aux, removed_edges)) if initial == None: initial = final data.insert(final) threshold += step_size for i in data.get_heap(): print("Threshold: ", i.threshold) print("Ratio: ", i.ratio) while data.heap_size > 0 and data.get_top().ratio == initial.ratio: data.extract() final_data = heap.Heap(lambda a, b: (a.threshold > b.threshold), True) final = data.extract() final_data.insert(final) while data.heap_size > 0 and data.get_top().ratio == final.ratio: final_data.insert(data.extract()) return final_data.get_top()
def test_max_heapify(self): # case : when the node has no child node binary_heap = heap.Heap([-1, 2]) binary_heap.max_heapify(1) self.assertEqual(binary_heap.heap, [-1, 2]) # case : when the node has at least one child node binary_heap = heap.Heap([-1, 1, 14, 16, 2, 8, 7]) binary_heap.max_heapify(1) self.assertEqual(binary_heap.heap, [-1, 16, 14, 7, 2, 8, 1])
def find_shortest_path(start_point, end_point): """ An implementation of Djikstra's algorithm for computing shortest paths. :param start_point: the source node object :param end_point: the destination node object :return: List of node objects corresponding to the shortest weighted path if a path exists. Otherwise, returns None. """ cost = dict() cost[start_point] = 0 visited = dict() visited[start_point] = None q = heap.Heap() q.insert(start_point, cost[start_point]) while q: current = q.pop() steps = list() steps.append(slide(current, 'left')) steps.append(slide(current, 'up')) steps.append(slide(current, 'right')) steps.append(slide(current, 'down')) for n in steps: if n not in cost: cost[n] = cost[current] + 1 visited[n] = current q.insert(n, cost[n]) if end_point in cost: return retrace_old_path(start_point, end_point, visited) else: return None
def test_delete_min(self): hp = heap.Heap(is_min=True) hp.add(heap.HeapNode(value=5)) hp.add(heap.HeapNode(value=9)) hp.add(heap.HeapNode(value=3)) hp.delete(10) hp.delete(1) assert hp.heap_arr[1] == 5 hp.delete(heap.HeapNode(value=5)) assert hp.heap_arr[1] == 9 #def test_delete_min(self): # heap = Heap() # heap.add(HeapNode(value = 5)) # heap.add(HeapNode(value = 9)) # heap.add(HeapNode(value = 3)) # heap.add(HeapNode(value = 7)) # heap.add(HeapNode(value = 11)) # heap.add(HeapNode(value = 1)) # print heap # print heap.pop() # print heap # heap.delete(2) # print heap # while(len(heap.heap_arr)>1): # print heap.pop(),",", # print "\n"
def nearest_neighbor_index(self, config_rand, tree_type, custom_nearest_neighbor=0): """ nearest_neighbor_index returns index of self.nearest_neighbor nearest neighbors of config_rand on the tree specified by treetype. """ if (tree_type == FORWARD): tree = self.tree_forward amount_vertex = len(tree) else: tree = self.tree_backward amount_vertex = len(tree) distance_list = [ self.distance(config_rand, vertex_hat.config, self.metric_type) for vertex_hat in tree.vertex_list ] distance_heap = heap.Heap(distance_list) if (custom_nearest_neighbor == 0): nearest_neighbor = self.nearest_neighbor else: nearest_neighbor = custom_nearest_neighbor if (nearest_neighbor == -1): nearest_neighbor = amount_vertex else: nearest_neighbor = min(self.nearest_neighbor, amount_vertex) nearest_neighbor_index = [ distance_heap.extract_min()[0] for i_range in range(nearest_neighbor) ] return nearest_neighbor_index
def dkt(G, s_label, t_label, use_heap=1): """ Using Dijkstra's algorithm to find the MAX_BANDWIDTH from source to destination. G is a graph represented by adjacency list, the labels for vertices in which must be consecutive positive integers. s_label is the unique label for source vertex t_label is the unique label for destination vertex """ if(use_heap != 1): return dkt_no_heap(G, s_label, t_label) h = heap.Heap(G.V, []) parent = array.array('I', [0] * (h.max_size + 1)) for v in G.adj_list[1:]: h[v.label] = 0 parent[v.label] = 0 h[s_label] = graph.MAX_EDGE_WEIGHT while (h.has(t_label) ): u_label_weight = h.pop() if(h[u_label_weight[0]] == 0): break u = G[u_label_weight[0]] for v_label_weight in u.list: new_bandwidth = min(h[u_label_weight[0]], v_label_weight[1]) if(new_bandwidth > h[v_label_weight[0]]): h[v_label_weight[0]] = new_bandwidth parent[v_label_weight[0]] = u_label_weight[0] return [h[t_label], parent]
def __init__(self, graph, vertex, source, dest): self.graph = graph self.vertex = vertex self.source = source self.dest = dest self.status = {} self.dad = {} self.bw = {} self.heap = heap.Heap() for v in vertex: self.status[v] = UNSEEN self.bw[v] = sys.maxint self.dad[v] = None if (source not in graph or dest not in graph): print "dijkstra.py: Invalid source or destination. Exiting." exit(0) self.status[source] = INTREE for v in graph[source]: self.dad[v] = source self.status[v] = FRINGE # INSERT INTO HEAP self.bw[v] = graph[source][v] # UPDATE TO HEAP (self.heap).insert(v, graph[source][v])
def camino_minimo(grafo, desde, hasta): """que nos devuelva una lista con el camino mínimo entre ese par de sedes. Ejemplo: `camino_minimo(rusia, ‘Moscu’, ‘Saransk’) -> [‘Moscu’, ‘Samara’, ‘Saransk’]""" distancia = {} padre = {} visitado = {} for V in grafo.ver_vertices(): distancia[V] = INFINITO distancia[desde] = 0 padre[desde] = None q = HEAP.Heap(comparar_peso_invertido) q.heap_encolar([desde, distancia[desde]]) visitado[desde] = True while not q.heap_esta_vacio(): v, p = q.heap_desencolar() for w in grafo.adyacentes(v): if w in visitado: continue peso = grafo.peso_arista(v, w) if (distancia[v] + peso < distancia[w] or distancia[w] == INFINITO): padre[w] = v distancia[w] = distancia[v] + peso q.heap_encolar([w, distancia[w]]) # if w == hasta: # return seguir_camino(desde,hasta,padre) return seguir_camino(desde, hasta, padre)
def testMaxHeapBuild(self): data = [ 98, 45, 69, 85, 34, 66, 10, 2, 11, 3, 21, 30, 91, 32, 55, 74, 93, 17, 67, 19 ] h = heap.Heap(data) self.assertTrue(is_heap(h))
def test_right(): H = heap.Heap(25) assert H.right_child(4) == 10 assert H.right_child(3) == 8 assert H.right_child(2) == 6 assert H.right_child(1) == 4 assert H.right_child(0) == 2
def testMinHeapPushPop(self): # Test Push h = heap.Heap([], heap.HeapType.minheap) h.push(5) self.assertEqual(str(h), "[5]") h.push(7) self.assertEqual(str(h), "[5, 7]") h.push(3) self.assertEqual(str(h), "[3, 7, 5]") h.push(4) self.assertEqual(str(h), "[3, 4, 5, 7]") h.push(-1) self.assertEqual(str(h), "[-1, 3, 5, 7, 4]") # Test peek self.assertEqual(h.peek(), -1) # Test pop self.assertEqual(h.pop(), -1) self.assertEqual(h.pop(), 3) self.assertEqual(h.pop(), 4) self.assertEqual(h.pop(), 5) h.push(-10) self.assertEqual(h.pop(), -10)
def __kruskals(g): t = [] uf = UnionFind() tot_w = 0 for v in g.get_all_vertices(): uf.make_set(v, lambda x: x.get_id()) edges = g.get_all_edges_list() h = heap.Heap(lambda x, y: x.get_data() < y.get_data()) list(map(lambda x: h.insert(x), edges)) print() print("Heap array after heapify:") print(h.get_data()) print() print("Heap array after sort:") for i in range(h.size()): e = h.dequeue() print('{}, '.format(e), end='') u = e.get_start() v = e.get_end() u_set = uf.find_set(u) v_set = uf.find_set(v) if u_set is not v_set: tot_w += e.get_data() t.append(e) uf.join(u, v) print() return t, tot_w
def __dijkstras(g, s): """ :param g: graph :param s: source node :return: """ prev = {} visited = {} for u, vmap in g.outgoing().items(): prev[u] = None visited[u] = False u.set_data('oo') s.set_data(0) q = heap.Heap(lambda x, y: x.get_data() < y.get_data()) q.insert(s) while q.size(): u = q.dequeue() visited[u] = True adj = g.adjacent_nodes(u) for v in adj: node = g.outgoing()[u][v] d = node.get_data() alt = u.get_data() + d if v.get_data( ) == 'oo' or alt < v.get_data() and not visited[v]: v.set_data(alt) prev[v] = u q.insert(v) return prev
def test_left(): H = heap.Heap(25) assert H.left_child(4) == 9 assert H.left_child(3) == 7 assert H.left_child(2) == 5 assert H.left_child(1) == 3 assert H.left_child(0) == 1
def test_extract_max(self): # test whether the return value of extract_max is the max value in the heap binary_heap = heap.Heap([-1, 20, 10, 16, 8, 7, 13, 14, 2, 5, 6]) max_value = max(binary_heap.heap) self.assertEqual(binary_heap.extract_max(), max_value) # test the heap is organized properly after the binary heap removed the root self.assertEqual(binary_heap.heap, [-1, 16, 10, 14, 8, 7, 13, 6, 2, 5])
def using_heaps(dist): hp = h.Heap() best_node = 'undefined' for v in dist: hp.add_to_heap(dist[v]) if dist[v] == hp.minimum(): best_node = v return best_node
def test_add_min(self): hp = heap.Heap() hp.add(heap.HeapNode(value=5)) assert hp.heap_arr[1] == 5 hp.add(heap.HeapNode(value=9)) assert hp.heap_arr[2] == 9 hp.add(heap.HeapNode(value=3)) assert hp.heap_arr[1] == 3
def test_add_max(self): hp = heap.Heap(is_min=False) hp.add(heap.HeapNode(value=5)) assert hp.heap_arr[1] == 5 hp.add(heap.HeapNode(value=9)) assert hp.heap_arr[1] == 9 hp.add(heap.HeapNode(value=3)) assert hp.heap_arr[3] == 3
def test_sort(self): cont = heap.Heap() tab = [heap.Node(i, (0, 0), i) for i in reversed(range(10))] for i in tab: cont.insert(i) for e in sorted(tab): self.assertEqual(e, cont.pop())
def test_with_heap(size): priority_queue = heap.Heap() for i in range(size): rand = random.randint(1, size) priority_queue.push(rand) top10 = [priority_queue.pop() for _ in range(10)] print("Top 10 (with heap):", top10)
def test_insert(): H = heap.Heap(25) X = [79, 87, 28, 6, 46, 66, 17, 1, 58, 94] for val in X: H.insert(val) Expected = [1, 6, 17, 28, 46, 79, 66, 87, 58, 94] for i in range(0, len(Expected)): assert H.data[i] == Expected[i]
def test_swap(): H = heap.Heap(25) H.insert(1) H.insert(2) H.insert(3) H.swap(0, 2) assert H.data[0] == 3 assert H.data[2] == 1
def testPeek(self): testHeap = h.Heap() testHeap.insert(3) testHeap.insert(5) testHeap.insert(4) testHeap.insert(2) testHeap.insert(14) testHeap.insert(12) testHeap.insert(11) self.assertEqual(testHeap.peek(), 2)
def ascending(self): ret = list() h = heap.Heap(False) for val in self.list: h.insert(val) for i in range(len(self.list)): ret.append(h.remove()) return ret
def test_delete_max(self): hp = heap.Heap(is_min=False) hp.add(heap.HeapNode(value=5)) hp.add(heap.HeapNode(value=9)) hp.add(heap.HeapNode(value=3)) hp.delete(10) hp.delete(1) assert hp.heap_arr[1] == 5 hp.delete(heap.HeapNode(value=5)) assert hp.heap_arr[1] == 3
def test_build_max_heap(self): test_set = [[-1, 1, 14, 16, 2, 8, 7], [-1, 8, 12, 6, 11, 10, 2, 3, 1], [-1, 2, 3], [-1, 5], [-1, 4, 7, 8, 9, 10]] answer_set = [[-1, 16, 14, 7, 2, 8, 1], [-1, 12, 11, 6, 8, 10, 2, 3, 1], [-1, 3, 2], [-1, 5], [-1, 10, 9, 8, 4, 7]] for i in range(len(test_set)): binary_heap = heap.Heap(test_set[i]) binary_heap.build_max_heap() self.assertEqual(test_set[i], answer_set[i])
def test_heap_creation(): min_heap = heap.Heap() for i in range(10): min_heap.put(randrange(1, 100)) print(min_heap) first_item = min_heap.get() print('Got {0} from the heap'.format(first_item)) print(min_heap)
def modified_dijkstra(graph, source, destination): time = {} prev = {} #Vlad arrives at his first station at 6 time[source] = 18 min_heap = atlas_heap.Heap() for vertex in graph: if vertex != source: time[vertex] = float("inf") prev[vertex] = None #Worst Case: log(V) min_heap.insert(time[vertex],vertex) while not min_heap.empty(): #Worst Case: log(V) u = min_heap.deleteMin() current_time = u[0] current_vertex = u[1] for neighbor in graph[current_vertex]: edge = graph[current_vertex][neighbor] departure_time = edge['departure_time'] travel_time = edge['travel_time'] #O(1) op due to custom hash table implementation neighbor_heap_node = min_heap.getByName(neighbor) arrival_time = special_mod(current_time) #calculating the value of the next node #We arrived after the possible departure time, so we have to wait the day if arrival_time > departure_time: #Do thing waiting_time = 24+departure_time-arrival_time else: #We've arrived before departure so we don't have to wait waiting_time = departure_time-arrival_time alt = waiting_time+travel_time+current_time if alt < time[neighbor]: time[neighbor] = alt neighbor_heap_node.data = alt prev[neighbor] = current_vertex #Worst Case: log(V) min_heap.decreaseKey(neighbor_heap_node) if destination not in time or time[destination] == float("inf"): return -1 else: blood_bags = round(time[destination]/24)-1 return blood_bags