def ui(): min_heap = Heap(is_max=False) max_heap = Heap() next = input() while next != "": min_heap.insert(next) if min_heap._size() > max_heap._size() + 1: max_heap.insert(min_heap.pop_top()) # print min_heap, max_heap running_median = min_heap.top() if min_heap._size() > max_heap._size( ) else (float(min_heap.top()) + max_heap.top()) / 2 print str(running_median) next = input()
def NearestNeighborIndices(self, c_rand, treetype, custom_nn=0): """NearestNeighborIndices returns indices of self.nn nearest neighbors of c_rand on the tree specified by treetype. """ if (treetype == FW): tree = self.treestart nv = len(tree) else: tree = self.treeend nv = len(tree) distancelist = [ self.Distance(c_rand, v.config) for v in tree.verticeslist ] distanceheap = Heap.Heap(distancelist) if (custom_nn == 0): nn = self.nn else: nn = custom_nn if (nn == -1): #using all of the vertexes in the tree nn = nv else: nn = min(self.nn, nv) nnindices = [distanceheap.ExtractMin()[0] for i in range(nn)] return nnindices
def prim(self, identifier): ''' Returns the minimum generating tree by the prim ''' for v in self.vertices.values(): v.c = 'white' v.pi = None v.d = float('inf') v.f = float('inf') self.vertices[identifier].d = 0 H = Heap([], True, True) for v in self.getAdjacents(identifier): edge = (identifier, ) + v H.insert(HeapItem(edge[2], edge)) while len(H) != 0: u = H.extract() dist = u[2] if dist < self.vertices[u[1]].d: self.vertices[u[1]].pi = u[0] self.vertices[u[1]].d = dist for v in self.getAdjacents(u[1]): edge = (u[1], ) + v H.insert(HeapItem(edge[2], edge)) P = [] for v in self.vertices.values(): if v.id != identifier: edge = (v.id, v.pi, v.d) P.append(edge) return P
def insights(self, table_name: str, result_size: int, insight_dimension: List[int]) -> List[ComponentExtractor]: """ :param table_name: :type table_name: str :param result_size: :type result_size: int :param insight_dimension: the dimension that each Extractor used to measure. :type insight_dimension: List[int], ex. [measurement, D0, D1, D2, ...] :return: :rtype: sorted List[ComponentExtractor] """ self.__initialization(table_name, insight_dimension) heap = Heap(result_size) possible_Ce = self.__enumerate_all_Ce() for Ce in possible_Ce: for subspace_id in range(len(self.__subspace_attr_ids)): S = Subspace.create_all_start_subspace( self.__subspace_dimension) self.__enumerate_insight(S, subspace_id, Ce, heap) return heap.get_nlargest()
def heapSort(unsortedList): result = [] a = Heap() a.buildMaxHeap(unsortedList) while a.size > 0: result.append(a.extractMax()) return result[::-1]
def dijkstra(adjGraph, root): #initialize all vertices for word in adjGraph: vertexDict[word].setKey(float('inf')) vertexDict[word].setPredecessor(None) #initialize the root to 0 vertexDict[root].setKey(0) #INITIALIZE HEAP (PRIORITY QUEUE) priorityHeap = Heap() for v in vertexDict: priorityHeap.insert(vertexDict[v]) #While priority queue is not empty while priorityHeap.getHeapsize() > 0: #remove min of heap u = priorityHeap.removeMin() #iterate through the adjacency list of u for v in adjGraph[u.getWord()]: uKey = vertexDict[u.getWord()].getKey() + weight(u, v) #relax the graph if uKey < vertexDict[v.getWord()].getKey(): vertexDict[v.getWord()].setPredecessor(vertexDict[u.getWord()]) vertexDict[v.getWord()].setKey(uKey) priorityHeap.heapifyUp(vertexDict[v.getWord()].getHandle()) return priorityHeap
def mergeSortedArrays(arrays): sorted_array = [] array_pointers = [0 for array in arrays] min_heap = Heap.Heap([], comparison_func) for i in range(len(arrays)): min_heap.insert([i, arrays[i][0]]) while not min_heap.is_empty(): next_sorted_element = min_heap.remove() sorted_array.append(next_sorted_element[1]) array_of_next_element_idx = next_sorted_element[0] array_pointers[array_of_next_element_idx] += 1 if array_pointers[array_of_next_element_idx] == len( arrays[array_of_next_element_idx]): continue min_heap.insert([ array_of_next_element_idx, arrays[array_of_next_element_idx][ array_pointers[array_of_next_element_idx]] ]) return sorted_array
def merge_sort(ls_arrays): # heap to store the next first items from lists min_heap = Heap(is_max=False) # parallel array keep track of the next item next_items = [0] * len(ls_arrays) # push firsts on to heap for ndx, ele in enumerate(ls_arrays): if ele: next_items[ndx] += 1 min_heap.insert(HeapNodes(ele[0], ndx)) res = [] while not min_heap.is_empty(): # pop the next one from the heap --> O(logn) nxt = min_heap.pop_top() res.append(nxt.data) pos = nxt.origin # if still more to push on to the heap, push the next one and move pointer forward if next_items[pos] < len(ls_arrays[pos]): next_to_insert = ls_arrays[pos][next_items[pos]] min_heap.insert(HeapNodes(next_to_insert, pos)) next_items[pos] += 1 return res
def HeapSort(list, pc): heap = Heap.Heap(pc) for i in xrange(len(list)): heap.heapPush(list[i]) for i in xrange(len(list)): list[i] = heap.heapPop()
def heapsort(x): """ Sort list x using Heap Sort. x remains unchanged """ h = Heap.Heap() y = x[:] h.heapify(y) return([h.pop() for i in range(h.size())])
def test_method(): h = Heap.Heap() random_test = random.sample(range(0, 100), 10) print(random_test, "\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n") for num in random_test: h.insert(num) print("Heap array: %s\n" % h.heap_array) print("_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n") print("The min-heap with this set of numbers is:\n", h.heap_array)
def __init__(self, ActivityIDList, StartTimeList, FinnalTimeList, n): self.Length = n self.ActivityList = [] for i in range(self.Length): self.ActivityList.append( self.ActivityEntity(ActivityIDList[i], StartTimeList[i], FinnalTimeList[i])) Comparetor = lambda Object1, Object2: True if Object1.FinnalTime > Object2.FinnalTime else False self.ActivityHeap = Heap(self.ActivityList, Comparetor, -float('inf'))
def add_node(self, nw_topo_g, rn): # print 'adding node ' + rn next = {} distance = Heap() visited = [] # for [n,d] in nw_topo_g.nodes(data=True): # distance.push(sys.maxint, n, sys.maxint) distance.push(0, rn, sys.maxint) return self.threshold_based_bfs(nw_topo_g, rn, self.theta_init, visited, distance, next)
def read_file_to_heap(file): '''reads from file numbers seperated by commas''' heap = Heap.Heap() for_heap = io.open(file, 'r+', encoding="UTF-8") for line in for_heap: a = line.split(',') print("The file reads:-------------", a) for num in a: heap.insert(float(num)) return heap
def test_arr12(self): heap = Heap.Heap() a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] arr = heap.MakeHeap(a, 3) count = 0 for i in arr: if i != None: count += 1 self.assertEqual(len(a) == count, True, 'digits are incorrect') self.assertEqual(len(arr) == 15, True, 'None are incorrect') self.assertEqual(arr[0] == 12, True, 'first elem are incorrect')
def __enumerate_insight(self, S: Subspace, subspace_id: int, Ce: ComponentExtractor, heap: Heap, index=[], verbose=False): """ :param S: :type S: Subspace :param subspace_id: :type subspace_id: int :param Ce: :type Ce: ComponentExtractor :param heap: :type heap: Heap """ local_heap = Heap(heap.capacity) SG = self.__generate_sibling_group(S, subspace_id) # phase I if self.__is_valid(SG, Ce): if verbose: print(f'\t subspace_id: {subspace_id}, index: {index}') phi = self.__extract_phi(SG, Ce) imp = self.__imp(SG) for _, insight_type in enumerate(InsightType): if imp == 0: continue score = imp * self.__sig(phi, insight_type) if score > local_heap.get_max().score: new_Ce = Ce.deepcopy() new_Ce.score = score new_Ce.insight_type = insight_type new_Ce.SG = SG local_heap.push(new_Ce) heap.push(new_Ce) # phase II for aid, attr_val in enumerate( self.__dom[self.__subspace_attr_ids[subspace_id]]): # Di S_ = S[:] S_[subspace_id] = attr_val.deepcopy() for j in range(len(S_)): # Dj if S_[j].type == AttributeType.ALL: self.__enumerate_insight(S_, j, Ce, heap, index=[index, subspace_id, aid], verbose=verbose)
def huffman_coding(d): h = Heap.Heap() for x in d: h.put(d[x], x) while h.size() > 1: a = h.get() b = h.get() c = a[0] + b[0] h.put(c, (a, b)) return h.get()
def test_correct_form(self): heap = Heap.Heap() a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] arr = heap.MakeHeap(a, 3) count = 0 for i in range(len(arr)): if arr[i] != None and 2 * i + 1 < len(a) - 1 or 2 * i + 2 < len( a) - 1: self.assertEqual(arr[i] > arr[2 * i + 1], True, 'form are incorrect') self.assertEqual(arr[i] > arr[2 * i + 2], True, 'form are incorrect')
def get_grid_experiment_inputs(run_location, bw_map_file, theta_inits): group_mem_ia_rd_dict = {} group_id_ip_bw_dict = {} l2bm_theta_obj_dict = {} sender_sched_f = run_location + '/group_sender_sched.txt' group_bw_f = bw_map_file group_mem_ia_rd_f = run_location + '/group_mem_ia_rd.txt' group_mem_ia_rd_str_key = eval(open(group_mem_ia_rd_f, 'r').read()) for k, v in group_mem_ia_rd_str_key.iteritems(): group_mem_ia_rd_dict[int(k)] = v group_sender_inter_arrival_ls = np.array(eval( open(sender_sched_f, 'r').read()), dtype=float) group_id_ip_bw_str_key = utils.get_group_bw_dict(group_bw_f) for k, v in group_id_ip_bw_str_key.iteritems(): group_id_ip_bw_dict[int(k)] = int(v[1]) / 1000 # print group_id_ip_bw_dict[int(k)] group_sender_arrivals = np.cumsum(group_sender_inter_arrival_ls) ev_heap = Heap() ev_list = [] event_index = 0 # print 'range(len(group_mem_ia_rd_dict))', range(len(group_mem_ia_rd_dict)) dst_obj_ls = [None for _ in range(len(group_mem_ia_rd_dict))] dst_lb_obj_ls = [None for _ in range(len(group_mem_ia_rd_dict))] for theta in theta_inits: l2bm_theta_obj_dict[theta] = [ None for _ in range(len(group_mem_ia_rd_dict)) ] for k, v in group_mem_ia_rd_dict.iteritems(): sender_arrival_tiime = group_sender_arrivals[k] source = v[0][0] del v[0] bw = group_id_ip_bw_dict[int(k)] dst = DynamicSteinerTree(source, bw) dst_lb = DynamicSteinerTreeLB(source, bw) dst_obj_ls[int(k)] = dst dst_lb_obj_ls[int(k)] = dst_lb for theta in theta_inits: l2bm_theta_obj_dict[theta][int(k)] = L2BM(source, bw, int(theta)) cumsum_arrival_time = sender_arrival_tiime for r_info in v: recv, i_a, rd = r_info cumsum_arrival_time += i_a me = MulticastEvent(int(k), source, int(bw), recv, cumsum_arrival_time, 'join') item_id = event_index event_index += 1 ev_heap.push(cumsum_arrival_time, item_id, me) while not ev_heap.is_empty(): r_a, item_id, ev = ev_heap.pop() ev_list.append((r_a, ev)) return ev_list, dst_obj_ls, dst_lb_obj_ls, l2bm_theta_obj_dict
def solution(n, times): answer = 0 i = 0 heap = Heap.Heap() for value in times: for i in range(1, n): heap.insert_heap(value * i) print(heap.heap_data) for i in range(n - 1): heap.remove_heap() print(heap.heap_data) answer = heap.heap_data[1] return answer
def main(): h = Heap.Heap() # Test Heap sort for correctness x = [random.randint(1, 1000) for i in range(10)] x1 = sorted(x) x2 = Sort.heapsort(x) print x1 == x2 # Print the n smallest elements h.heapify(x) print h.nsmallest(5)
def heap_sort(heap_list): h = Heap.Heap() i = len(heap_list) // 2 - 1 while i >= 0: h.percolate_down(i, heap_list, len(heap_list)) i = i - 1 i = len(heap_list) - 1 while i > 0: temp = heap_list[0] heap_list[0] = heap_list[i] heap_list[i] = temp h.percolate_down(0, heap_list, i) i = i - 1
def create_sched_heap_congested_traffic(no_of_groups, mean_receiver_inter_arrival, no_of_receiver_per_group, group_bandwidths, theta_inits, candidate_nodes, nodes_weight=None): ev_heap = Heap() ev_list = [] dst_obj_ls = [] dst_lb_obj_ls = [] l2bm_theta_obj_dict = {} for theta in theta_inits: l2bm_theta_obj_dict[theta] = [] event_index = 0 sender_inter_arrival_time = np.random.exponential(2, no_of_groups) sender_arrival_time = np.cumsum(sender_inter_arrival_time) # concentrated_nodes = np.random.choice(candidate_nodes, no_of_receiver_per_group+1, replace=False).tolist() for n in range(0, no_of_groups): receiver_inter_arrival_time = np.random.exponential( mean_receiver_inter_arrival, no_of_receiver_per_group) # print receiver_inter_arrival_time receiver_arrival_time = np.add(np.cumsum(receiver_inter_arrival_time), sender_arrival_time[int(n)]) # print receiver_arrival_time receivers = np.random.choice(candidate_nodes, no_of_receiver_per_group + 1, replace=False, p=nodes_weight).tolist() source = receivers.pop(0) bw = group_bandwidths[n] dst = DynamicSteinerTree(source, bw) dst_lb = DynamicSteinerTreeLB(source, bw) for theta in theta_inits: l2bm_theta_obj_dict[theta].append(L2BM(source, bw, int(theta))) dst_obj_ls.append(dst) dst_lb_obj_ls.append(dst_lb) for r_n, r_a in itertools.izip(receivers, receiver_arrival_time): me = MulticastEvent(n, source, int(bw), r_n, r_a, 'join') item_id = event_index event_index = event_index + 1 # print item_id ev_heap.push(r_a, item_id, me) while not ev_heap.is_empty(): r_a, item_id, ev = ev_heap.pop() ev_list.append((r_a, ev)) return ev_list, dst_obj_ls, dst_lb_obj_ls, l2bm_theta_obj_dict
def test_more_arr(self): heap = Heap.Heap() a = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [6, 5, 2, 1, 3, 8, 11, 4, 9, 7], [7, 5], [5, 7, 8, 4, 10]] for i in a: arr = heap.MakeHeap(i, 3) count = 0 for j in arr: if j != None: count += 1 self.assertEqual(len(i) == count, True, 'digits are incorrect') self.assertEqual(len(arr) == 15, True, 'None are incorrect') self.assertEqual(arr[0] == max(i), True, 'first elem == max element are incorrect')
def HUFFMAN(C): n = len(C) comparetor = lambda Object1, Object2: True if Object1.freq < Object2.freq else False CharacterHeap = Heap(C, comparetor, float('inf')) for i in range(0, n - 1): HuffmanTree = HuffmanNode() HuffmanTree.left = CharacterHeap.Heap_Extract_Max_Or_Min() print "HuffmanTree.left.freq = ", print HuffmanTree.left.freq HuffmanTree.right = CharacterHeap.Heap_Extract_Max_Or_Min() print "HuffmanTree.right.freq = ", print HuffmanTree.right.freq HuffmanTree.freq = HuffmanTree.left.freq + HuffmanTree.right.freq CharacterHeap.Heap_Insert(HuffmanTree) return CharacterHeap.Heap_Extract_Max_Or_Min()
def add_node(self, nw_topo_g, rn): # print 'adding node ' + rn tree_node_found = False distance = Heap() visited = [] next = {} distance.push(0, rn) nn = rn while not distance.is_empty(): dist, nn, dnn = distance.pop() # print 'Q pop nn -> '+ nn if nn in visited: continue if nn in self.tree.nodes(): tree_node_found = True # print 'tree node found' break visited.append(nn) for u, n, d in nw_topo_g.in_edges(nn, data=True): if u in visited or int(d['bandwidth']) < int(self.bandwidth): continue bw_cap = float(d['capacity']) # print 'bw_cap '+ str(bw_cap) bw_cons = float(bw_cap) - (float(d['bandwidth']) - float(self.bandwidth)) # print 'bw_cons '+ str(bw_cons) bw_util = float(bw_cons) * 100 / float(bw_cap) new_dist_u = float(dist) + float(bw_util) dist_u_max_util = distance.get_key(u) if dist_u_max_util is not None: dist_u, u_max_util = dist_u_max_util if dist_u < new_dist_u: continue distance.push(new_dist_u, u) next[u] = n if tree_node_found: self.leaf_nodes.append(rn) while nn != rn: ns = next[nn] self.tree.add_edge(nn, ns) bw = int(nw_topo_g.edge[nn][ns][0]['bandwidth']) nw_topo_g.edge[nn][ns][0]['bandwidth'] = bw - int( self.bandwidth) data = nw_topo_g.edge[nn][ns][0]['bandwidth'] # print str(nn) + '->' +str(ns) nn = ns return tree_node_found
def return_k_largest(heap, k): # takes a max heap, and a integer k, returns k largest elements from the heap k = min(heap._size(), k) max_heap = Heap() max_heap.insert(HeapNodes(heap.top(), 1)) result = [] for i in range(k): top = max_heap.pop_top() result.append(top.data) ndx = top.origin child = ndx * 2 if child <= heap._size(): max_heap.insert(HeapNodes(heap.nth(child), child)) if child + 1 <= heap._size(): max_heap.insert(HeapNodes(heap.nth(child + 1), child + 1)) return result
def test_max_arr(self): heap = Heap.Heap() a = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [6, 5, 2, 1, 3, 8, 11, 4, 9, 7], [11, 5], [5, 7, 8, 4, 10]] for j in a: arr = heap.MakeHeap(j, 3) arr_res = [] for i in arr: if i != None: arr_res.append(i) print(arr_res) del arr_res[0] arr_max = heap.GetMax() print(arr_max, max(arr_res)) self.assertEqual(arr_max == max(arr_res), True, 'first element are incorrect')
def add_node(self, nw_topo_g, rn): # print 'DynamicSteinerTree:Source:'+self.source_node+' adding node ' + rn visited = [] tree_node_found = False distance = Heap() next = {} distance.push(0, rn) nn = rn while not distance.is_empty(): dist, nn, dnn = distance.pop() # print 'Q pop nn -> '+ nn if nn in visited: continue visited.append(nn) if nn in self.tree.nodes(): tree_node_found = True # print 'tree node found' break for u, n, d in nw_topo_g.in_edges(nn, data=True): if (u in visited) or (int(d['bandwidth']) < int( self.bandwidth)): continue # print u + '->'+nn new_dist_u = dist + 1 dist_u_max_util = distance.get_key(u) if dist_u_max_util is not None: dist_u, u_max_util = dist_u_max_util if dist_u < new_dist_u: continue distance.push(new_dist_u, u) next[u] = n if tree_node_found: self.leaf_nodes.append(rn) while nn != rn: ns = next[nn] self.tree.add_edge(nn, ns) bw = int(nw_topo_g.edge[nn][ns][0]['bandwidth']) nw_topo_g.edge[nn][ns][0]['bandwidth'] = bw - int( self.bandwidth) if bw - int(self.bandwidth) < 0: print self.source_node, rn, self.bandwidth data = nw_topo_g.edge[nn][ns][0]['bandwidth'] # print str(nn) + '->' +str(ns) nn = ns return tree_node_found
def Dijkstra(edges, start, d): begin = timeit.default_timer() A = [None] * len(edges) queue = Heap.Heap(d) queue.insert((0, start)) while queue.size != 0: path_len, v = queue.pop() if A[v] is None: # v is unvisited A[v] = path_len for w, edge_len in edges[v].items(): if A[w] is None: queue.insert((path_len + edge_len, w)) # to give same result as original, assign zero distance to unreachable vertices # return [0 if x is None else x for x in A] end = timeit.default_timer() return (end - begin)