def test_max_heap(): print("Running tests") print("-------------") a = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1] my_heap = heap(a) print("Testing parents, left, right") assert (my_heap.parent(1) == 0) assert (my_heap.parent(2) == 0) assert (my_heap.left(0) == 1) assert (my_heap.right(0) == 2) print("Testing max_heapify") # Test behavior as in Figure 6.2 (page 131) a = [16, 4, 10, 14, 7, 9, 3, 2, 8, 1] my_heap = heap(a) my_heap.max_heapify(1) assert (my_heap.A == [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]) print("Testing build_max_heap") # Test behavior as in Figure 6.3 (page 134) a = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] my_heap = heap(a) my_heap.build_max_heap() assert (my_heap.A == [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]) print("Testing heapsort") a = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1] my_heap = heap(a) my_heap.heapsort() assert (my_heap.A == [1, 2, 3, 4, 7, 8, 9, 10, 14, 16]) print("-------------") print("All tests passed") print("")
def singleStore(self, lst): targLst = [] wallLst = [] a = heap.heap(1) b = heap.heap(2) for i in lst: print(i.data) # print(i.data) if i.data[3] == "target": targLst.append(i) self.cursor.execute("SELECT * FROM search_type WHERE id = %s", (i.data[5],)) searchTerm = self.cursor.fetchone()[1] c = bayesFilter.naivebayes(bayesFilter.getwords, searchTerm, self.database, self.cursor) self.cursor.execute("SELECT * FROM search_type WHERE search = %s", (searchTerm,)) results = self.cursor.fetchall() for j in results: if j[3] == "walmart": pass else: toup = (j.data[0], j.data[1], j.data[2], j.data[3], c.prob(j.data[0], 1), j.data[4]) a.push(toup) targLst.append(a.sort()[0]) else: wallLst.append(i) self.cursor.execute("SELECT * FROM search_type WHERE id = %s", (i.data[5],)) searchTerm = self.cursor.fetchone()[1] c = bayesFilter.naivebayes(bayesFilter.getwords, searchTerm, self.database, self.cursor) self.cursor.execute("SELECT * FROM search_type WHERE search = %s", (searchTerm,)) results = self.cursor.fetchall() # print(results) for j in results: self.cursor.execute("SELECT * FROM food WHERE id = %s", (j[0],)) r = self.cursor.fetchone() if r[3] == "target": pass else: toup = (r[0], r[1], r[2], r[3], c.prob(r[0], 1), r[4]) a.push(toup) wallLst.append(a.sort()[0]) targTot = 0 wallTot = 0 for i in targLst: targTot += i.data[4] for i in wallLst: wallTot += i.data[4] print(targTot) print(wallTot) return (targLst,wallLst)
def predict_evil_order(n, E, G, Gin, pij): ep, em, houtm, hout = 0, 0, np.zeros(n), np.zeros(n) hinm, hin = np.zeros(n), np.zeros(n) ref = {e: abs(0.5 - pij(*e)) for e in E} hpij = {e: 0 for e in E} pred, gold = [], [] edges = heap({e: (hpij[e], ref[e]) for e in ref}) while edges: u, v = edges.pop() s = E[(u, v)] gold.append(s) p = my_rule(houtm[u], hout[u], hinm[v], hin[v], 0.5 if (ep+em) == 0 else ep/(ep+em)) pred.append(p) hout[u] += 1 houtm[u] += int(s < 0) hin[v] += 1 hinm[v] += int(s < 0) savev = v for v in G[u]: if (u, v) in edges: hpuv = (houtm[u] + hinm[v])/(hout[u] + hin[v]) edges[(u, v)] = (abs(.5 - hpuv), ref[(u, v)]) v = savev for u in Gin[v]: if (u, v) in edges: hpuv = (houtm[u] + hinm[v])/(hout[u] + hin[v]) edges[(u, v)] = (abs(.5 - hpuv), ref[(u, v)]) return (np.array(pred) != np.array(gold)).cumsum()
def test_larger(self): h = heap() for i in range(10, 0, -1): h.insert(i) for i in range(1, 11): self.assertEquals(i, h.extract_min())
def dijkstra(G,n,s): '''implementation with heap''' l=0 hq=range(1000000) #heap for G-V vertices r={} # result hash table mapvtoindex={} #map the vertices to hq index for fast search and update found={} #boolean to record the vertices whose short pathes are currently found hpobj=heap.heap(hq,l) for i in xrange(1,n+1): found[i]=False if i==s: hpobj.heappush(hq,[0,s],mapvtoindex) else: hpobj.heappush(hq,[1000000,i],mapvtoindex) while hpobj.length(hq): p=hpobj.heappop(hq,mapvtoindex) v=p[1] r[v]=p[0] found[v]=True e_list=G[v] for i in xrange(len(e_list)): w=e_list[i][0] if found[w]==False: d=r[v]+e_list[i][1] if d<hq[mapvtoindex[w]][0]: hq[mapvtoindex[w]][0]=d #relax the path, decrease the key for vertex w hpobj.heapify_up(hq,mapvtoindex[w],mapvtoindex) #heapify vertex w locally return r
def __init__(self): self.heap = heap.heap("epoch") self.seconds_job_dict = {} self.heap_lock = threading.Lock() self.seconds_dict_lock = threading.Lock() self.executor_tid = None self.mgr_started = False
def dijkstraH(self,node1,node2=-1): X = [] path = [] first = node1 self.D[first] = 0 N = self.Nodes() H = heap.heap(len(N)) H.setCmpF(self.compareD) H.heapify(N) while not H.empty(): nextN = H.extractMin() if nextN == node2: return self.D[nextN] #, X if nextN in X: print H.l() raise NameError("duplicate node in X") for head in self.heads(nextN): greedy = self.D[nextN] + self.l(nextN,head) if head not in X and self.D[head] > greedy: self.D[head] = greedy H.updateVal(H.find(head), head) X.append(nextN) return self.D
def Shortest_Path(Graph,start,end): for i in Graph.nodes: i.distance = 0 i.parent = -1; tovisit = heap(ceil(2+Graph.num_nodes/Graph.num_edges)) #create d-heap where d is ceil(2+m/n) tovisit.push((0,start)) #push a tuple with node label and node number (node label first to sort heap by this) while(tovisit.h): visit_node = tovisit.pop() #get the minimum cost neighbor visit_node_id = visit_node[1] #print('visiting: ',visit_node_id) visit_node_label = visit_node[0] for i in range(0,len(Graph.nodes[visit_node_id].children['end'])): #check all children even if they have already been visited neighbors = Graph.nodes[visit_node_id].children if(Graph.nodes[neighbors['end'][i]].distance > visit_node_label + neighbors['weight'][i] or Graph.nodes[neighbors['end'][i]].parent == -1): # update if the label from this node is less or if the node hasn't been visited #print('count of ',i['end'],'is ',[x[1] for x in tovisit.h].count(i['end'])) if([x[1] for x in tovisit.h].count(neighbors['end'][i]) != 0): #if node is already in heap, remove it index = [x[1] for x in tovisit.h].index(neighbors['end'][i]) tovisit.delete(index) Graph.nodes[neighbors['end'][i]].parent = visit_node_id #update neighbor Graph.nodes[neighbors['end'][i]].distance = visit_node_label + neighbors['weight'][i] #print('adding',i['end'],'with distance',Graph.nodes[i['end']].distance) tovisit.push((Graph.nodes[neighbors['end'][i]].distance,neighbors['end'][i])) #put node on heap return get_path(Graph,start,end)
def prim(G): key_q = heap([-1]) #dummy. index start at 1 key = [-1] pi = [0] * (len(G) + 1) key.append(0) key_q.append(0) for i in range(1, len(G)): key_q.append(math.inf) key.append(math.inf) key_q.build_max_heap() pinkNode = [] while len(key_q) > 1: u = key.index(key_q.extract_min()) pinkNode.append(u) for v in G[u]: if v not in pinkNode and G[u][v] < key[v]: if key[v] == math.inf: key_q.extract_max() else: key_q.remove(key[v]) key_q.append(G[u][v]) key[v] = G[u][v] pi[v] = u return pi
def dijkstra(G): d = [math.inf] * (len(G) + 1) d[1] = 0 S = [] Q = heap([-1]) key = [-1] for i in range(0, len(G)): key.append(math.inf) Q.append(math.inf) key[1] = 0 Q[1] = 0 while len(Q) > 1: u = key.index(Q.extract_min()) S.append(u) for v in G[u]: if d[v] > d[u] + G[u][v]: d[v] = d[u] + G[u][v] if key[v] == math.inf: Q.extract_max() else: Q.remove(key[v]) key[v] = d[u] + G[u][v] Q.append(d[u] + G[u][v]) Q.build_max_heap() return d
def dijkstra(G, n, s): '''implementation with heap''' l = 0 hq = range(1000000) #heap for G-V vertices r = {} # result hash table mapvtoindex = {} #map the vertices to hq index for fast search and update found = { } #boolean to record the vertices whose short pathes are currently found hpobj = heap.heap(hq, l) for i in xrange(1, n + 1): found[i] = False if i == s: hpobj.heappush(hq, [0, s], mapvtoindex) else: hpobj.heappush(hq, [1000000, i], mapvtoindex) while hpobj.length(hq): p = hpobj.heappop(hq, mapvtoindex) v = p[1] r[v] = p[0] found[v] = True e_list = G[v] for i in xrange(len(e_list)): w = e_list[i][0] if found[w] == False: d = r[v] + e_list[i][1] if d < hq[mapvtoindex[w]][0]: hq[mapvtoindex[w]][ 0] = d #relax the path, decrease the key for vertex w hpobj.heapify_up(hq, mapvtoindex[w], mapvtoindex) #heapify vertex w locally return r
def heapsort_test(self, array): "Verifies that the heap can be used to sort array" h = heap.heap() for elem in array: h.insert(elem) sorted_array = sorted(array) for elem in sorted_array: self.assertEquals(h.extract_min(), elem)
def heapsort2(ar): h = heap() for e in ar: h.insert(e) r = [] for i in range(0, len(ar)): r.append(h.extract_min()) return r
def test1(self): "Insert one element and then delete it" h = heap.heap() self.assertEquals(h.A, [None]) self.assertEquals(h.heapsize, 0) h.insert(5) h.delete(1) self.assertEquals(h.A, [None]) self.assertEquals(h.heapsize, 0)
def test_insert(hp): keys = copy(hp.keys) new_hp = heap([], []) for k in keys: new_hp.insert(k, k) assert new_hp.keys == hp.keys _test_basic(hp)
def huffman(values): """Argument is a list of lists containing two elements, a value, and the value's weight""" tree = heap.heap() for value in values: tree.insert([node(weight = value[1], value = value[0]), value[1]]) while len(tree.list) > 1: min1 = tree.extractmin() min2 = tree.extractmin() tree.insert([node(left = min1, right = min2, weight = min1[1] + min2[1]), min1[1] + min2[1]]) return tree.list[0]
def __init__(self, num): x = 1 while x < int(num) + 1: #creates a list of all the vertices l = vertex(x) self.vertices.append(l) x = x + 1 self.vertices[0].setWeight(0) self.weights.append(None) for w in self.vertices: #creates a list of weights with index 0 being NULL self.weights.append(w.getWeight()) self.h = heap(self.weights, num) #creates a heap from the list
def heap_sort(list, max=True, min=False): is_max = max * (not min) ''' This function is a heap sort implemented using the class heap found in this same repo Note: This is a sort in place ''' sorted = [None for i in range(len(list))] heap_list = heap(list, is_max) for i, val in enumerate(heap_list.heap): index = -i - 1 if is_max else i list[index] = heap_list.get()
def heapG(self): h = heap.heap(501) h.setCmpF(self.cmpN) #h.heapify([ (min((cost,end) for (end,cost) in # self.Graph[node].items()) + (node,)) # for node in self.Graph.keys() ]) h.heapify(self.Graph.keys()) print h.extractMin() print h.extractMin() print h.extractMin()
def mst(src, graph): diss = {v: float('infinity') for v in graph.keys()} vals_dic = {} diss[src] = 0 prio_que = heap(diss.keys(), diss.values()) while not prio_que.is_empty(): cur_dist, cur_v = prio_que.pop() for neigh, weight in graph[cur_v].items(): if weight < prio_que.prio(neigh): prio_que.decrease_key(neigh, weight) vals_dic[neigh] = cur_v return vals_dic
def test2(self): "Insert many elements and then delete one" h = heap.heap() h.insert(5) h.insert(15) h.insert(10) h.insert(0) h.delete(3) # delete 10 self.assertEquals(0, h.extract_min()) self.assertEquals(5, h.extract_min()) self.assertEquals(15, h.extract_min()) self.assertEquals(h.A, [None]) self.assertEquals(h.heapsize, 0)
def test(): print("Running tests") print("-------------") # test extract max print("Testing heap extract max") a = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1] my_heap = heap(a) heap_max = my_heap.heap_extract_max() assert(my_heap.A == [14, 8, 10, 4, 7, 9, 3, 2, 1, 1]) # test increase key (as in Fig. 6.5 on page 141) print("Testing heap increase key") a = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1] my_heap = heap(a) my_heap.heap_increase_key(8, 15) #(5, 17) #(3, 15) assert(my_heap.A == [16, 15, 10, 14, 7, 9, 3, 2, 8, 1]) # test max heap insert print("Testing max heap insert") a = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1] my_heap = heap(a) my_heap.max_heap_insert(5) #(5, 17) #(3, 15) assert(my_heap.A == [16, 14, 10, 8, 7, 9, 3, 2, 4, 1, 5]) # test build max heap prime print("Testing build max heap prime") a = [2, 7, 4, 1, 16, 10, 9, 3, 14, 8] my_heap = heap(a) my_heap.build_max_heap_prime() res = my_heap.validate_max_heap() assert(res == True) assert(my_heap.A == [16, 14, 10, 7, 8, 4, 9, 1, 3, 2]) print("-------------") print("All tests passed") print("")
def test0(self): "Test original heap functionality" h = heap.heap() import random for i in range(20): h.insert(random.randint(0, 10)) l = [] while h.heapsize > 0: l.append(h.extract_min()) self.assertEquals(len(l), 20) for i in range(len(l) - 1): self.assertTrue(l[i] <= l[i + 1]) self.assertEquals(h.heapsize, 0) self.assertEquals(h.A, [None])
def test11(self): "Insert four elements and then delete all four" h = heap.heap() self.assertEquals(h.A, [None]) self.assertEquals(h.heapsize, 0) h.insert(5) h.insert(8) h.insert(7) h.insert(6) h.delete(1) h.delete(3) h.delete(2) h.delete(1) self.assertEquals(h.A, [None]) self.assertEquals(h.heapsize, 0)
def minimum_spanning_tree(graph, weights, root=0): connection_cost = heap({v: 0 if v == root else sys.maxsize for v in graph}) connection_edge = {v: None for v in graph} outside = set(graph.keys()) tree = [] while connection_cost: v = connection_cost.pop() outside.remove(v) if connection_edge[v] is not None: tree.append(connection_edge[v]) for w in graph[v]: edge = (v, w) if v < w else (w, v) if w in outside and weights[edge] < connection_cost[w]: connection_cost[w] = weights[edge] connection_edge[w] = edge return tree
def test_internals(self): h = heap() h.insert(5) h.insert(4) h.insert(3) h.insert(2) self.assertEquals(-1, h.parent(0)) self.assertEquals(0, h.parent(1)) self.assertEquals(0, h.parent(2)) self.assertEquals(1, h.left_child(0)) self.assertEquals(2, h.right_child(0)) self.assertEquals(3, h.left_child(1)) self.assertEquals(4, h.right_child(1)) self.assertEquals(5, h.left_child(2)) self.assertEquals(6, h.right_child(2)) self.assertEquals(2, h.parent(6))
def sortList(): myList = heap([]) print("This program sorts a list of integers using a heap abstraction.\n") length = validateInt("How long would you like your list to be?: ") print("Please enter {} integers in any order to fill your list:".format( length)) for i in range(length): myList.appendList(validateInt("")) print("The order of your list as entered:") myList.printList() print("\nYour sorted list:") myList.sortHeap() myList.printList()
def search(self, searchTerm, glst, quantity): c = bayesFilter.naivebayes(bayesFilter.getwords, searchTerm, self.database, self.cursor) querySearchTerm = ("SELECT * FROM search WHERE name = %s") self.cursor.execute(querySearchTerm, (searchTerm,)) results = self.cursor.fetchall() if len(results) == 0: self.buildData(searchTerm) self.search(searchTerm,glst, quantity) return querySearch = ("SELECT * FROM search_type WHERE search = %s") self.cursor.execute(querySearch, (searchTerm,)) curs1 = self.cursor.fetchall() # results = cursor.fetchall() lst = [] for i in curs1: queryItem = ("SELECT * FROM food WHERE id = %s") self.cursor.execute(queryItem, (i[0],)) r = self.cursor.fetchone() # print(r) toup = (r[0], r[1], r[2], r[3], r[1]/r[2], r[4]) lst.append(toup) h = heap.heap(1) # print("hi") for i in lst: h.push(i) finalForm = h.sort() for i in finalForm: print(i.data) yn = input("is this the item you are looking for? y/n") if yn == "y": c.train(i.data[0],1) self.cursor.execute("INSERT INTO list_items " "(food_id, list_id, quantity) " "VALUES (%s,%s,%s)",(i.data[5],glst,quantity)) self.database.commit() self.cursor.execute("UPDATE search_type SET points = points + 1 WHERE id = %s", (i.data[5],)) self.database.commit() # print(finalForm) return finalForm c.train(i.data[0],0) return finalForm
def Shortest_Path(Graph, start, end): for i in Graph.nodes: i.distance = 0 i.parent = -1 tovisit = heap( ceil(2 + Graph.num_nodes / Graph.num_edges)) #create d-heap where d is ceil(2+m/n) tovisit.push( (0, start) ) #push a tuple with node label and node number (node label first to sort heap by this) while (tovisit.h): visit_node = tovisit.pop() #get the minimum cost neighbor visit_node_id = visit_node[1] #print('visiting: ',visit_node_id) visit_node_label = visit_node[0] for i in range( 0, len(Graph.nodes[visit_node_id].children['end']) ): #check all children even if they have already been visited neighbors = Graph.nodes[visit_node_id].children if ( Graph.nodes[neighbors['end'][i]].distance > visit_node_label + neighbors['weight'][i] or Graph.nodes[neighbors['end'][i]].parent == -1 ): # update if the label from this node is less or if the node hasn't been visited #print('count of ',i['end'],'is ',[x[1] for x in tovisit.h].count(i['end'])) if ([x[1] for x in tovisit.h].count(neighbors['end'][i]) != 0): #if node is already in heap, remove it index = [x[1] for x in tovisit.h].index(neighbors['end'][i]) tovisit.delete(index) Graph.nodes[neighbors['end'] [i]].parent = visit_node_id #update neighbor Graph.nodes[neighbors['end'][ i]].distance = visit_node_label + neighbors['weight'][i] #print('adding',i['end'],'with distance',Graph.nodes[i['end']].distance) tovisit.push((Graph.nodes[neighbors['end'][i]].distance, neighbors['end'][i])) #put node on heap return get_path(Graph, start, end)
def hide_edges(G, E, vis, fraction=.1): """hide some edges involving hidden node without deconnecting the graph""" degrees = {u: sum(adj.values()) for u, adj in G.items()} h_degrees = heap({u: -sum(adj.values()) for u, adj in G.items() if not vis[u]}) edges_hidden = set() num_edges_to_hid = int(fraction*len(E)) while h_degrees and len(edges_hidden) < num_edges_to_hid: u = h_degrees.pop() neighbors = sorted((v for v in G[u] if degrees[v] > max(2, .7*len(G[v]))), key=degrees.__getitem__, reverse=True) for v in neighbors: degrees[u] -= 1 degrees[v] -= 1 if v in h_degrees: h_degrees[v] += 1 edges_hidden.add((u, v) if u < v else (v, u)) if len(edges_hidden) >= num_edges_to_hid: break return edges_hidden
def rankASs(distances, min_transcripts=3): from heap import heap, heappop # @UnresolvedImport distance_list = [] contig_list = [] for transcript in distances.keys(): contigs = list(distances[transcript].keys()) if len(contigs) >= min_transcripts: for i in range(len(contigs)): sum_dist = 0 for j in range(len(contigs)): if i != j: sum_dist += distances[transcript][contigs[i]][ contigs[j]] contig_list.append(transcript + '_' + contigs[i]) distance_list.append(sum_dist / (len(contigs) - 1)) heap_distances, heap_contigs = heap(distance_list, contig_list) return heappop(heap_distances, heap_contigs)
# -*- coding: utf-8 -*- """ Created on Tue Feb 02 14:45:55 2016 @author: Shashank Viswanadha """ import heap myHeap = heap.heap(100) class cell: def __init__(self, element): self.element = element self.next = 0 def makeNull(): header = cell(None) myAdd = myHeap.malloc() if myAdd != -1: myHeap.set_cell(myAdd, header) return myAdd def pos(h, y): t = myHeap.get_cell(h) if t.element == y: return h else: h = t.next return pos(h, y)
def main(): A = map(int,raw_input().split()) h = heap(A) h.heapsort() h.printheap()
def heapsort(a): my_heap = heap(a) my_heap.heapsort() a = my_heap.A
if distA < queue.getMax(): self.childA.kNearest(position, queue) num = 1 << 10 print("Number of particles:", num) rg = np.random.default_rng() particles = np.zeros((num, 5)) particles[:,2] = np.ones(num) particles[:,0:2] = rg.random((num,2)) #plt.hist(particles[:,0]) root = Cell(0, 0, num, particles[:,0:3], [0,0], [1,1]) fig, axes = plt.subplots(1,2) for particle in particles: maxHeap = heap(32) root.kNearest(particle[0:2], maxHeap) # Monohan factor factor = (40 / (7*math.pi)) / (maxHeap.getMax() ** 2) sumMass = 0 sumMassMonohan = 0 for i in range(maxHeap.size): mass = maxHeap.data[i][2] sumMass += mass h = maxHeap.getMax() r = maxHeap.values[i] if r > 0 and r / h < 0.5: sumMassMonohan += mass * (6 * (r / h) ** 3 - 6 * (r / h) ** 2 + 1) elif r/h >= 0.5 and r / h <= 1:
def __init__(self, tabela, custo): self.tabela = tabela self.custo = custo self.filhos = [] self.heap = heap(self,self)
from utility import GenerateRandomArray from maximumsubarrayproblem import find_max_crossing_subarray from maximumsubarrayproblem import find_maximum_subarray from heap import heap Array=GenerateRandomArray(10) print(Array) h=heap(Array) print(h.array) h.heap_increase_key(5,400) print(h.array) h.max_heap_insert(300) print(h.array)
def extract_stars(graph, degree_function=None, threshold_function=None, X=None): # TODO values could include vertex indice to get stars of same degree in # topological order… if threshold_function: return _extract_stars_threshold(graph, threshold_function) pick_max_degree = degree_function is None if pick_max_degree: if X: degrees = heap({u: (1 - int(u in X), -len(adj)) for u, adj in graph.items()}) else: degrees = heap({u: -len(adj) for u, adj in graph.items()}) else: degrees = WeightedDegrees([len(graph[u]) for u in sorted(graph)], degree_function) used = {u: False for u in graph} not_in_stars = set(graph.keys()) stars, inner_edges = [], [] membership = {} while degrees: star_idx = len(stars) center = degrees.pop() if used[center]: continue star = Star(center, [p for p in graph[center] if not used[p]]) used[center] = True membership[center] = star_idx not_in_stars.remove(center) degree_changes = defaultdict(int) for p in star.points: used[p] = True membership[p] = star_idx not_in_stars.remove(p) for w in graph[p].intersection(not_in_stars): degree_changes[w] -= 1 if pick_max_degree: for node, decrease in degree_changes.items(): if X: inX, deg = degrees[node] degrees[node] = (inX, deg - decrease) else: degrees[node] -= decrease else: degrees.update_weights(degree_changes) stars.append(star) inner_edges.append(edges_of_star(star)) if not pick_max_degree: # when using the degree based sampling, some node may reach 0 weight # because all their neighbors have been grabbed by previous stars. # Therefore they can't be sampled anymore (whereas when using # max_degree, they stay in the queue with degree 0). So here we have to # manually create singleton. for u, in_star in used.items(): if in_star: continue assert degrees.degrees[u] == 0 star = Star(u, []) used[u] = True membership[u] = len(stars) not_in_stars.remove(u) stars.append(star) inner_edges.append([]) assert all(used.values()) assert len(not_in_stars) == 0 assert set(membership.keys()) == set(used.keys()) assert set(membership.values()) == set(range(len(stars))) return stars, inner_edges, membership
def heapsort(ar): h = heap(ar=ar) h.unwind() return ar
def heapSort(arr): heap = H.heap() for i in arr: heap.push(i) for i in range(len(arr)): arr[len(arr) - 1 - i] = heap.popMax()
#### esse site garante que havera solucao ## teste FACIL # inicio = [[1,2,3],[4,5,6],[7,8,'*']] # inicio = [['*',2,3],[1,5,6],[4,7,8]] ## teste RAZOAVEL inicio = [[6,7,3],[2,5,8],[4,1,'*']] # inicio = [[1,6,7],[8,5,2],[4,3,'*']] ## teste DIFICIL (nao resolve rapido) # inicio = [[1,3,5,7],[9,11,13,15],[2,4,6,14],[8,12,10,'*']] # inicio = [[1,3,5,7],[9,11,13,15],[2,4,6,14],[8,12,10,'*']] # cria a uma heap com a configuracao inicial r = heap(inicio,FcustoManhatan(inicio)) r.setAltura(0) mostrarTabela(inicio) # armazena todos os estados ja visitados # evita minimos locais EstadosVisitados = [] while True : # menor elemento da heap m = r.Menor() # remove o menor elemento da heap # evita revisitar estados
import sys sys.path.insert(0, 'C:/Users/sidd/Desktop/heap/') import heap myheap = heap.heap([5, 10, 22, 34, 1, 6]) myheap.show_heap() myheap.pop() myheap.show_heap()
__copyright__ = "Copyright 2017 Sampler Project" __credits__ = ["Andres Mendez-Vazquez"] __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "Andres Mendez-Vazquez" __email__ = "*****@*****.**" __status__ = "Development" __name__ = "__main__" import numpy as np from heap import heap if __name__ == "__main__": # Object heap HObject = heap() x = np.arange(10, dtype=np.int32) print(x) HObject.read_data(x) HObject.print_container() HObject.build_heap() HObject.print_container() print(HObject._length)
import heap import re myheap = heap.heap(300) class cell(): def __init__(self): self.ch = None self.rc = None self.lc = None self.val = 0 l = [] d = {} def analyze(fn): with open(fn, 'r') as f: for line in f: for char in line: if char in l: d[char] = d[char] + 1 else: l.append(char) d[char] = 1 return 0 analyze("one.txt")
else: print "mergesort incorrect." except: print "mergesort function errored or is incomplete." try: from quick import quick if (quick(list(nums)) == sortedNums): print "quicksort success!" else: print "quicksort incorrect." except: print "quicksort function errored or is incomplete." try: from heap import heap if (heap(list(nums)) == sortedNums): print "Heap Sort success!" else: print "Heap Sort incorrect." except: print "Heapsort function errored or is incomplete." try: from selection import selection if (selection(list(nums)) == sortedNums): print "Selection Sort success!" else: print "Selection Sort incorrect." except: print "Selection function errored or is incomplete."
def distance(a, b): diffX = abs(a.pos[0] - b.pos[0]) diffY = abs(a.pos[1] - b.pos[1]) return 14 * min(diffX, diffY) + 10 * abs(diffX - diffY) closed = set() #openlist = set() found = False start = nodes[1, 1] end = nodes[width * 2 - 1, height * 2 - 1] #openlist.add(start) print("Path finding") openlist = heap() openlist.add(start) while openlist.length() > 0: lowestF = float("inf") current = openlist.pop() closed.add(current) print("Current: ", current.pos, " Exit: ", end.pos) if current == end: found = True print("Found") break for neighbor in get_neighbours(current.pos, 1): node = nodes[neighbor[0], neighbor[1]] skip = False
def sort_degree(G): """Return a heap of nodes sorted by degree and a boolean (all false) array""" return (heap({node: -len(adj) for node, adj in G.items()}), [False for _ in G.keys()])
def test_heap(self): h = heap() h.insert(1) self.assertEqual(1, h.extract_min())
def event_cycle(cf): global reconfigure, shutdown, reopen, poll, poll_type, spare_processes, processes, num_processes, prepare_processes, processes_fds, processes_hash, old_processes_hash, queue, debug ctx = cf.conf['ctx'] queue = heap.heap(128, cmp_handler) i = 0 spare_processes = [] processes = [] processes_hash = {} processes_fds = {} num_processes = 0 prepare_processes = 0 now = time.time() for t in tasks: node = queue.node() node.data = {'next_time': now + random.uniform(0, t['interval']), 'task_id': i} queue.insert(node) i += 1 s = 0 while s < ctx['maxworkers']: processes.append({'id' : -1, 'pid' : -1, 'channel' : None, 'task_id' : -1, 'status' : ZC_PREPARE}) s+=1 set_master_signal() start_worker_processes(cf) rc = None increase_times = 0 decrease_times = 0 killed = False count_interval = ctx['count_interval'] start_time = time.time() last_count_time = start_time change_time = start_time do_tasks = 0 last_do_tasks = 0 while True: wait_process(cf) if shutdown: if num_processes == 0 and len(old_processes_hash) == 0: break time.sleep(0.1) if not killed: for pid in processes_hash: os.kill(pid, signal.SIGTERM) for pid in old_processes_hash: os.kill(pid, signal.SIGTERM) killed = True continue if reconfigure: time.sleep(0.1) sig = signal.SIGHUP for pid in processes_hash: os.kill(pid, sig) for pid in processes_hash: old_processes_hash[pid] = processes_hash[pid] set_master_signal2() break if reopen: cf.log.all("Reopen log file") try: cf.log.reopen(ctx['user']) except error, e: cf.log.error("%s" %(e)) shutdown = True continue if not debug: sys.stderr = cf.log.handlers[0].stream sys.stdout = cf.log.handlers[0].stream cf.log.debug("master reopened") sig = signal.SIGUSR1 for pid in processes_hash: os.kill(pid, sig) reopen = False now = time.time() s = queue.top() while s != None and s.data['next_time'] <= now and len(spare_processes) > 0: if shutdown or reconfigure or reopen: break process = spare_processes[-1] process['task_id'] = s.data['task_id'] fd = process['channel'][0].fileno() delay = now - s.data['next_time'] if delay > 1: cf.log.warn('start delay %f, queue busy' %(delay)) cf.log.debug("Send to fd %d" %(fd)) try: fd_send(fd, pack_task(process['task_id'])) except ZC_Error, e: if e[0] == errno.EINTR: continue # SIG_PIPE cf.log.error("Send to %d: %s" %(fd, e)) process['status'] = ZC_PREPARE prepare_processes += 1 spare_processes.pop() continue cf.log.debug("Poll regiser %d" %(fd)) poll.register(fd, poll.POLLIN) tasks[process['task_id']]['last_time'] = s.data['next_time'] process['status'] = ZC_BUSY spare_processes.pop() queue.delete(s) s = queue.top()
def __init__(self, file): self.minHeap = heap.heap(10005) self.minHeap.setCmpF(lambda n1, n2: n2 < n1) self.maxHeap = heap.heap(10000) self.fd = open(file, "rU") self.medians = []