Esempio n. 1
0
def heapSort(unsortedList):
	result = []
	a = Heap()
	a.buildMaxHeap(unsortedList)
	while a.size > 0:
		result.append(a.extractMax())
	return result[::-1]
def main():
    H= Heap.heap(lambda x,y: int(x.time) <= int(y.time),"H") #Creating a min heap for Harold
    C= Heap.heap(lambda x,y: int(x.cost) >= int(y.cost),"C") #Creating a max heap for Cathy
    filename = input('Enter the filename: ')
    print("\n")
    try:
        with open(filename) as f:
            for line in f:
                line=line.strip()
                line=line.split()
                if len(line) > 2:
                    newJob=jobsDone(line)
                    print('New Job arriving! Job Name:  ',line[0],line[1],line[2])
                    H.insert(newJob)
                    C.insert(newJob)
                else:
                    if(line[0] == "Cathy"):
                        job=C.pop()
                        if(job is not None):
                            print('Cathy starting job: ',job.name)
                            H.data[0],H.data[job.Hindex] = H.data[job.Hindex],H.data[0]
                            haroldRemovesjob= H.pop()
                            # print("Cathy's Heap: ", C)
                            # print("Harold's Heap after popping: ", H)
                    else:
                        job=H.pop()
                        if(job is not None):
                            print('Harold starting job: ',job.name)
                            C.data[0],C.data[job.Cindex] = C.data[job.Cindex],C.data[0]
                            cathyRemovesjob= C.pop()
                            # print("Cathy's Heap: ", C)
                            # print("Harold's Heap after popping: ", H)

    except FileNotFoundError as e:
        print(e)
Esempio n. 3
0
    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()
Esempio n. 4
0
    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'))
Esempio n. 5
0
 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)
Esempio n. 6
0
def link_recom(G, num, target):
    INFINITY = 100
    def sim(d1, d2):
        return 1/float(d1+d2-1)

    s = [0.0]*num;
    # for i in xrange(0, num):
    #     s[i] = 0.0

    degree = []
    for row in G:
        deg = 0.0
        for i in row:
            deg = deg + i
        degree.append(deg)

    H = [Node(-1, -1)]
    dist = [INFINITY]*num
    # for j in xrange(0, num):
    #     dist[j] = INFINITY
    threshold = 0.05

    v = target
    s[v]=1
    dist[v] = 0
    v0 = Node(v, 0)
    Heap.insert(H, v0)

    while len(H) > 1:
        v = Heap.get_min(H).name
        A = G[v]
        neighbor = [i for i in range(0, len(A)) if A[i] != 0.0]
        for k in neighbor:
            if dist[k]>dist[v]+G[v][k]:
                dist[k] = dist[v]+G[v][k]
                node_k = Node(k, dist[k])
                s[k] = s[v]*sim(degree[v], degree[k])
                if node_k not in H and s[k] >= threshold:
                    Heap.insert(H, node_k)

    # print 'sucessful'
    # print s
    # print H
    #print dist

    similarity ={}
    count = 0
    for i in s:
        similarity[count]=i
        count = count + 1

    sorted_sim = sorted(similarity.items(),key=lambda e:e[1], reverse=True)
    print "probability of relationship with target %s" % target
    print sorted_sim[1:]
Esempio n. 7
0
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 heapsort(Arr):
    """Sorting the given array in ascending order using heap data structure"""
    heap.build_max_heap(Arr)
    #print(Arr)
    new_arr = Arr[:]
    #node=0
    #while node
    for node in range(len(Arr) - 1, 0, -1):
        Arr[node], Arr[0], new_arr[node], new_arr[0] = new_arr[0], new_arr[
            node], new_arr[0], new_arr[node]
        #print('MH1>>{}{}'.format(Arr,new_arr))
        new_arr.pop()
        #print('MH2>>{}{}'.format(Arr,new_arr))
        heap.max_heapify(new_arr, 0)
Esempio n. 9
0
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
Esempio n. 10
0
    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 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
Esempio n. 12
0
class Activity:
    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 GreedyActivitySelectOR(self):
        self.ActivityHeap.HEAPSORT()
        ActivityMaxSubSet = []
        ActivityMaxSubSet.append(self.ActivityList[0].ActivityID)
        k = 0
        for m in range(1, self.Length):
            if self.ActivityList[m].StartTime >= self.ActivityList[
                    k].FinnalTime:
                ActivityMaxSubSet.append(self.ActivityList[m].ActivityID)
                k = m
        return ActivityMaxSubSet

    class ActivityEntity:
        def __init__(self, ActivityID, StartTime, FinnalTime):
            self.ActivityID = ActivityID
            self.StartTime = StartTime
            self.FinnalTime = FinnalTime
Esempio n. 13
0
File: Graph.py Progetto: gulaak/UCS
    def UCS(self, root, goal):
        pq = h.PriorityQueue()
        pq.enqueue((0, root, root))  # (priority, currnode, path)
        while (
                not (pq.empty())
        ):  # iterates till queue is empty otherwise until all nodes are exhausted
            print(pq.queue)
            node = pq.dequeue()
            if (
                    node[NODE] in goal
            ):  # if the current node in queue is equal to goal then we have print path
                print(node[PATH] + " Cost: " +
                      str(node[PRIORITY]))  # prints path
                break
            elif (self.visitedNodes[node[NODE]]):
                continue  #next iteration node has already been expanded
            else:
                self.visitNode(node[NODE])
                children = self.edges[node[NODE]]

                for childnode in children:
                    if (self.visitedNodes[childnode[NODE]] is not True):
                        pq.enqueue((childnode[PRIORITY] + node[PRIORITY],
                                    childnode[NODE],
                                    node[PATH] + "->" + str(childnode[NODE])
                                    ))  # enques all of the node children
                    else:
                        continue
Esempio n. 14
0
 def UCS(self, nodoInicial, nodoFinal):
     unaColaPrioridad = monticulo.PriorityQueue()
     unaColaPrioridad.insertarElemento((0, nodoInicial, nodoInicial))
     #una vez que se inicializa la cola de prioridad se chequea que no este vacia
     while (not (unaColaPrioridad.empty())):
         #prueba recorrido
         #            print(unaColaPrioridad.queue)
         node = unaColaPrioridad.eliminarElemento()
         #si se llega al nodo final
         if (node[NODE] in nodoFinal):
             #                print("Se llego al nodo final")
             print("Recorrido al nodo final: " + node[RECORRIDO] +
                   " Costo: " + str(node[COSTO]))
             break
         #sino recorre los nodoInicio
         elif (self.visitedNodes[node[NODE]]):
             continue
         #sino recorre los nodos hijos
         else:
             self.nodoVisitado(node[NODE])
             nodosHijos = self.conecciones[node[NODE]]
             for nodoHijo in nodosHijos:
                 if (self.visitedNodes[nodoHijo[NODE]] is not True):
                     unaColaPrioridad.insertarElemento(
                         (nodoHijo[COSTO] + node[COSTO], nodoHijo[NODE],
                          node[RECORRIDO] + "->" + str(nodoHijo[NODE])))
                 else:
                     continue
Esempio n. 15
0
def remove_from(heap, param):
    removed = heap.pop(0)
    last_element = heap.pop()
    heap.insert(0, last_element)
    heap = Heap.heapify(heap, param)

    return (removed, heap)
Esempio n. 16
0
def main():	
	
	#inputList = [5, 7, 10, 4, 1, 6, 8, 3]
	#inputList = [3,9,12,6]
	#inputList = [3,18,6,12,9]
	#inputList = [5,4,3,2,1]
	#inputList = [22, 41, 18, 9, 7, 8, 7, 10]
	#inputList = [2,1,3,0,2]
	inputList = [1,16,5,30,27,17,20,2,57,3,90]
	n = len(inputList)
	outputList = [None]*n


	print('\nA entrada é: ', inputList)

	print('\nOrdenando com CountingSort...')

	CS.CountingSort(inputList.copy(), outputList, n)

	print('Lista ordenada:', outputList)

	print('\n\nA entrada é: ', inputList)
	print('\nOrdenando com HeapSort...')	

	HP.HeapSort(inputList.copy())
Esempio n. 17
0
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()
Esempio n. 18
0
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())])
Esempio n. 19
0
 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
Esempio n. 20
0
File: Table.py Progetto: mkhi26/AED
    def getMatrixLevels(self):
        heap = Heap()
        n = len(self.l)
        hight = heap.getHight(n)
        width = heap.getWidth(hight)
        matrix = []
        for i in range(hight):
            n = 2**i

            start = n - 1
            end = heap.getWidth(i + 1) + start
            matrix.append(self.l[start:end])
        if len(matrix[-1]) < width:

            for i in range(width - len(matrix[-1])):
                matrix[-1].append(" ")

        return matrix
Esempio n. 21
0
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)
Esempio n. 22
0
def min_heapify(A:Heap, i):
    '''
    Maintains the min heap property: A[i] <= A[left(i)] && A[i] <= A[right(i)]
    '''
    if i >= A.size or i < 0:
        raise "i is not a valid index"

    left = A.left(i)
    right = A.right(i)
    smallest = i
    if left is not None and A.data[left] <= A.data[i]:
        smallest = left
    if right is not None and A.data[right] <= A.data[smallest]:
        smallest = right
    if i != smallest:
        # Then min heap property is violated
        A.data[smallest], A.data[i] = A.data[i], A.data[smallest]
        min_heapify(A, smallest)
Esempio n. 23
0
def max_heapify(A:Heap, i):
    '''
    Maintains the max heap property: A[i] >= A[left(i)] && A[i] >= A[right(i)]
    '''
    if i >= A.size or i < 0:
        raise "i is not a valid index"

    left = A.left(i)
    right = A.right(i)
    largest = i
    if left is not None and A.data[left] >= A.data[i]:
        largest = left
    if right is not None and A.data[right] >= A.data[largest]:
        largest = right
    if i != largest:
        # Then max heap property is violated
        A.data[largest], A.data[i] = A.data[i], A.data[largest]
        max_heapify(A, largest)
Esempio n. 24
0
    def insights(self,
                 table_name: str,
                 result_size: int,
                 insight_dimension: List[int],
                 in_memory=True,
                 verbose=False) -> 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, in_memory)

        heap = Heap(result_size)
        possible_Ce = self.__enumerate_all_Ce()

        print('Possible Ce:')
        print(possible_Ce)
        print('Number of Ce:', len(possible_Ce), '\n')

        for Ce_idx, Ce in enumerate(possible_Ce):
            start = time.time()
            print(f'Start Ce {Ce_idx}: {Ce}')
            for subspace_id in range(len(self.__subspace_attr_ids)):
                print(f'\tStart subspace id {subspace_id}')
                self.__enumerate_insight(self.__S,
                                         subspace_id,
                                         Ce,
                                         heap,
                                         verbose=verbose)
                print(
                    f'\tComplete subspace id {subspace_id}: Time Elapse {time.time() - start} sec'
                )

            print(
                f'Complete Ce {Ce_idx}: Time Elapse {time.time() - start} sec')

        return heap.get_nlargest()
Esempio n. 25
0
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 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
Esempio n. 27
0
 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')
Esempio n. 28
0
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
Esempio n. 29
0
def encode(frequencies):
  # Construct priority queue with high priorities for low frequencies.
  p = Heap()
  for char, freq in frequencies.iteritems():
    p.insert((freq, char))
  # Special cases
  if len(frequencies) == 0:  # Empty input
    return HuffmanNode()
  if len(frequencies) == 1:  # Repetition of same characters
    return HuffmanNode(p.pop()[1])
  # Construct Huffman tree.
  while len(p) > 1:
    left = p.pop()
    right = p.pop()
    node = HuffmanNode(left[1], right[1])
    p.insert((left[0] + right[0], node))
  return p.pop()[1]
Esempio n. 30
0
 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 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()
Esempio n. 32
0
 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
Esempio n. 33
0
def max_heapify_recur(A:Heap, i):
    '''
    A recursive version of max_heapify
    For Ex6.2-5
    '''
    if i >= A.size or i < 0:
        raise "i is not a valid index"

    while i < A.size:
        left = A.left(i)
        right = A.right(i)
        largest = i
        if left is not None and A.data[left] >= A.data[i]:
            largest = left
        if right is not None and A.data[right] >= A.data[largest]:
            largest = right
        if i != largest:
            # Then max heap property is violated
            A.data[largest], A.data[i] = A.data[i], A.data[largest]
            i = largest
        else:
            break
Esempio n. 34
0
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
Esempio n. 35
0
    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)
Esempio n. 36
0
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
Esempio n. 37
0
 def sort_asc_heap_sort(self):
     heap = Heap()
     heap.heap = self.list
     heap.heap_sort()
     return heap.heap
Esempio n. 38
0
def build_max_heap2(A: Heap):
    # PS 6.1
    n = A.size
    A.size = 1
    for i in range(1, n):
        A.max_heap_insert(A.data[i])
Esempio n. 39
0
def TestHeap():
    array = [0] * 10
    sortedArray = [0] * 10
    hsize = 9
    asize = 10

    myHeap = Heap()

    print("Inserting the values 4, 8, 3, 7, 2, 6, 9, 1, 5 in that order.\n")

    array[1] = HeapInt(4)
    myHeap.insert(array[1])

    array[2] = HeapInt(8)
    myHeap.insert(array[2])

    array[3] = HeapInt(3)
    myHeap.insert(array[3])

    array[4] = HeapInt(7)
    myHeap.insert(array[4])

    array[5] = HeapInt(2)
    myHeap.insert(array[5])

    array[6] = HeapInt(6)
    myHeap.insert(array[6])

    array[7] = HeapInt(9)
    myHeap.insert(array[7])

    array[8] = HeapInt(1)
    myHeap.insert(array[8])

    array[9] = HeapInt(5)
    myHeap.insert(array[9])

    ("value  handle")
    print("-----  ------")

    for i in range(1, hsize+1):
        print("  " + str(array[i].getKey()) + "       " + str(array[i].getHandle()))
	

    print("\n\nPrinting heap with printHeap(): \n")
	
    myHeap.printHeap()
	
    print("\nChanging value at root from 1 to 11 and heapifying down.")
	
    array[8].setKey(11)
	
    myHeap.heapifyDown(array[8].getHandle())
	
    print("\nRevised handle info:\n")
    print("value  handle")
    print("-----  ------")
	
    for i in range(1, hsize+1):
        print("  " + str(array[i].getKey()) + "       " + str(array[i].getHandle()))

    print("\n\nSorting by removing minimum at each step:\n")

    while (myHeap.getHeapsize() > 0):
        print( str(myHeap.removeMin().getKey()) + "  ")

    print("\n")