Exemplo n.º 1
0
 def test_len(self):
     heap = Heap(lambda a, b: a <= b)
     sequence = [5, 9, 3, 4, 6, 2, 0, 8, 7, 1]
     self.assertEqual(0, len(heap))
     for index, item in enumerate(sequence):
         heap.insert(item)
         self.assertEqual(index + 1, len(heap))
Exemplo n.º 2
0
    def __init__(self, userId, castSelector, clientManager, logManager):
        super(ABCASTManager, self).__init__()
        self.clock = 0
        self.clockMutex = threading.Lock()
        self.logManager = logManager

        self.userId = userId
        self.inputPipe = PIPE()
        self.outputPipe = PIPE()
        self.castManager = castSelector

        self.responseReceiver = {}
        self.receiverMutex = threading.Lock()

        self.clientList = clientManager.fetch_user_list()
        self.clientListMutex = threading.Lock()
        self.clientManager = clientManager

        self.processQueue = Heap()
        self.heapMutex = threading.Lock()

        self.recvProc = CustomThread(self._startReceiveMessage)
        self.sendProc = CustomThread(self._startSendBroadCast)

        self.pauseFlag = False
        self.startFlag = False
        self.waitCondition = threading.Condition()
Exemplo n.º 3
0
class PQueue:
    """This is a priority queue implementation"""
    def __init__(self,A):
        self._heap = Heap(A)

    def __str__(self):
        return str(self._heap.heap[1:])

    def peekMax(self):
        return self._heap[1]
    
    def extractMax(self):
        if self._heap.heapsize < 1:
            raise Exception("Heap underflow!")
        _max = self._heap[1]
        self._heap[1] = self._heap[self._heap.heapsize]
        self._heap.heapsize -= 1
        self._heap.maxHeapify(1)
        return _max
    
    def increaseKey(self,i,key):
        if key < self._heap[i]:
            raise Exception("New key is smaller than current key")
        self._heap[i] = key
        while i > 1 and self._heap[self._heap.Parent(i)] < self._heap[i]:
            self._heap[i],self._heap[self._heap.Parent(i)] = self._heap[self._heap.Parent(i)],self._heap[i]
            i = self._heap.Parent(i)
    
    def insert(self,key):
        self._heap.append(float("-inf"))
        self.increaseKey(self._heap.heapsize,key);
Exemplo n.º 4
0
def runEngine(tokenizer_type, address):
    print("RUNNING ENGINE ...")
    inverted_index = load_obj("INVERTED INDEX " + tokenizer_type + "_" +
                              address)
    tfidfs = load_obj("CHAMPIONS " + tokenize_type + "_" + address)

    query = ""

    while True:
        query = input("QUERY :>")
        if query == "!q": break

        queryToken = query.split(" ")
        queryw = tf_idf(queryToken, inverted_index, False)

        h = Heap()

        for i in range(len(tfidfs)):
            if bool(set(queryToken) & set(tfidfs[i].keys())):
                sim = querySimilarity(queryw, tfidfs[i])
                if sim != 0:
                    h.addnSort([i, sim])

        k = 10
        result = h.getFirstK(k)
        titles = fetch_column(address, 'title')
        for i in range(k):
            print(titles[result[i][0]][::-1])
Exemplo n.º 5
0
def test_push():
    """Test push method."""
    from Heap import Heap
    hl = Heap()
    hl.push(data[0])
    hl.push(data[1])
    assert hl.hl[1] == data[1]
Exemplo n.º 6
0
def kruskals(graphs):
    
    cost_matrix = [[-1 for i in range(0,graphs.vertices)] for j in range(0,graphs.vertices)]
    mst = graph(graphs.vertices,cost_matrix)
    heap = Heap()
    for i in range(0,graphs.vertices):
        for j in range(0,len(graphs.adj[i])):
            if graphs.cost_matrix[i][graphs.adj[i][j]-1] >0:
                heap.insert(i+1,graphs.adj[i][j],graphs.cost_matrix[i][graphs.adj[i][j]-1])

   

    edgesadd=0
    left = graphs.vertices
    mfset = Mfset(left)
    
    while(edgesadd<graphs.vertices-1):
       
        minimum = heap.pop_min()
      
      
        
        set1 = mfset.find(minimum[1])
        set2 = mfset.find(minimum[0])

        if set1 == set2:
            if set1 == 0:
                mfset.insertnew(minimum[1])
                mfset.insert(minimum[0],mfset.nosets)
                mst.add_edge(minimum[1],minimum[0])
                mst.cost_matrix[minimum[1]-1][minimum[0]-1]=graphs.cost_matrix[minimum[1]-1][minimum[0]-1]
                mst.cost_matrix[minimum[0]-1][minimum[1]-1]=graphs.cost_matrix[minimum[0]-1][minimum[1]-1]
                edgesadd=edgesadd+1
            else:
                # print(mfset.setarray)
                continue
        else:
            if set1 ==0:
                mfset.insert(minimum[1],set2)
                mst.add_edge(minimum[1],minimum[0])
                mst.cost_matrix[minimum[1]-1][minimum[0]-1]=graphs.cost_matrix[minimum[1]-1][minimum[0]-1]
                mst.cost_matrix[minimum[0]-1][minimum[1]-1]=graphs.cost_matrix[minimum[0]-1][minimum[1]-1]
                edgesadd = edgesadd+1
            elif set2 == 0:
                mst.add_edge(minimum[1],minimum[0])
                mst.cost_matrix[minimum[1]-1][minimum[0]-1]=graphs.cost_matrix[minimum[1]-1][minimum[0]-1]
                mst.cost_matrix[minimum[0]-1][minimum[1]-1]=graphs.cost_matrix[minimum[0]-1][minimum[1]-1]
                mfset.insert(minimum[0],set1)    
                edgesadd = edgesadd+1
            else:
                mst.add_edge(minimum[1],minimum[0])
                mst.cost_matrix[minimum[1]-1][minimum[0]-1]=graphs.cost_matrix[minimum[1]-1][minimum[0]-1]
                mst.cost_matrix[minimum[0]-1][minimum[1]-1]=graphs.cost_matrix[minimum[0]-1][minimum[1]-1]
                mfset.merge(set1,set2)
                edgesadd = edgesadd+1

        # print(mfset.setarray)
       

    return mst
 def __init__(self, arr: Optional[list] = None, k: int = 10, sort_key=lambda x: x):
     self.k = k
     self.sort_key = sort_key
     self.min_heap = Heap(type="min", sort_key=sort_key)
     if arr:
         for e in arr:
             self.insert(e)
Exemplo n.º 8
0
    def __init__(self, config):
        super().__init__()

        self.config = config

        # Open the log file for reading and seek to the end of it.
        self.logHandle = open(self.config.logFilePath)
        self.logHandle.seek(0, 2)

        # This parser is used to parse every log line.
        self.logParser = apache_log_parser.make_parser(LogStats.LOG_FORMAT)
        # If the first parser fails, we try this one.
        self.logParserAlt = apache_log_parser.make_parser(
            LogStats.LOG_FORMAT_ALT)

        # This lock grants exclusive access to data structures below.
        self.lock = Lock()

        # Various statistics.
        self.numHits = 0  # Total number of requests.
        self.numBadLines = 0  # Number of log lines that could not be parsed.
        self.responseBytesTot = 0  # Total response bytes sent.
        self.retCode2count = defaultdict(int)  # Count for each status code.
        self.method2count = defaultdict(int)  # Count for each request method.

        # This heap keeps track of all sections we have seen so far and their counts.
        self.heap = Heap()

        # Create the alerter and start its event loop in a separate process.
        self.alerter = Alerter(self.config.numHitsToGenAlert,
                               self.config.alertWinLenSecs)
        self.alerterProc = multiprocessing.Process(
            target=self.alerter.runAlerter)
        self.alerterProc.start()
Exemplo n.º 9
0
 def test_multifield_heapsort(self):
     heap = Heap(lambda a, b: a.daysUntilTrigger <= b.daysUntilTrigger and a
                 .urgency >= b.urgency and a.difficulty <= b.difficulty)
     heap.push_list(self.testList)
     for a, c in zip(heap.popper(), self.controlList):
         self.assertEqual(a.daysUntilTrigger, c.daysUntilTrigger)
         self.assertEqual(a.urgency, c.urgency)
         self.assertEqual(a.difficulty, c.difficulty)
Exemplo n.º 10
0
 def test_peek(self):
     heap = Heap(lambda a, b: a <= b)
     sequence = [5, 9, 3, 4, 6, 2, 0, 8, 7, 1]
     min_items = [5, 5, 3, 3, 3, 2, 0, 0, 0, 0]
     self.assertRaises(IndexError, heap.peek)
     for item, min_item in zip(sequence, min_items):
         heap.insert(item)
         self.assertEqual(min_item, heap.peek())
Exemplo n.º 11
0
 def test_max(self):
     heap = Heap(lambda a, b: a >= b)
     sequence = [5, 3, 4, 6, 2, 0, 8, 9, 7, 1]
     max_items = [5, 5, 5, 6, 6, 6, 8, 9, 9, 9]
     self.assertRaises(IndexError, heap.peek)
     for item, max_item in zip(sequence, max_items):
         heap.insert(item)
         self.assertEqual(max_item, heap.peek())
Exemplo n.º 12
0
 def test_iter(self):
     heap = Heap(lambda a, b: a <= b)
     sequence = [5, 9, 3, 4, 6, 2, 0, 8, 7, 1]
     heap.extend(sequence)
     dump = [x for x in heap]
     self.assertEqual(len(sequence), len(dump))
     self.assertEqual(0, dump[0])
     self.assertEqual(set(sequence), set(dump))
Exemplo n.º 13
0
 def test_multifield_heapsort(self):
   heap = Heap(lambda a,b: a.daysUntilTrigger <= b.daysUntilTrigger 
         and a.urgency >= b.urgency and a.difficulty <= b.difficulty)
   heap.push_list(self.testList)
   for a,c in zip(heap.popper(),self.controlList):
     self.assertEqual(a.daysUntilTrigger,c.daysUntilTrigger)
     self.assertEqual(a.urgency,c.urgency)
     self.assertEqual(a.difficulty,c.difficulty)
Exemplo n.º 14
0
 def __init__(self, G, s):
     self.G = G
     self.s = s
     self.h = Heap(self.G.V())
     for i in range(self.G.V()):
         self.h.insert(i, self.G.adjmat[self.s][i])
     self.adjlist = [[0, 0, 0] for i in range(self.G.V())]
     self.count = 0
Exemplo n.º 15
0
def heapSort(arr):
    heap = Heap(arr)
    sorted = []
    for i in range(len(heap.heap)):
        sorted.append(heap.heap[0])
        heap.heap[0] = -heap.heap[0] # Fill the end with values that will definitely stay there
        heap.heapify()
    return sorted
Exemplo n.º 16
0
class WeightBasedExpReplay(object):
    def __init__(self, maxSize, alpha=0.6, epsilon=0.000001):
        self.maxSize = maxSize
        self.buffer = Buffer(self.maxSize)
        self.sumTree = SumTree(self.maxSize)
        self.weights = {}
        self.alpha = 0.6
        self.curSize = 0
        self.epsilon = epsilon
        self.heap = Heap()

    def addExperience(self, experience):
        weight = self.heap.getMaxPriority()
        index = self.buffer.getPointer()
        self.buffer.insert(experience)
        prevWeight = 0
        if index in self.weights:
            prevWeight = self.weights[index]
        diffWeight = weight - prevWeight
        self.weights[index] = weight
        self.sumTree.insert(diffWeight, index)
        self.heap.add(index, weight)
        self.curSize = min(self.curSize + 1, self.maxSize)

    def modifyExperience(self, weight, index):
        weight = weight + self.epsilon
        weight = weight**self.alpha
        prevWeight = 0
        if index in self.weights:
            prevWeight = self.weights[index]
        diffWeight = weight - prevWeight
        self.weights[index] = weight
        self.sumTree.insert(diffWeight, index)
        self.heap.add(index, weight)

    def sample(self, samplesAmount):
        startPoints = np.linspace(0, self.sumTree.getAllSum(),
                                  samplesAmount + 1).tolist()
        expList = []
        weightList = []
        indexList = []
        for a in range(len(startPoints) - 1):
            start = startPoints[a]
            end = startPoints[a + 1]
            sampledNum = np.random.uniform(start, end)
            retrIndex = self.sumTree.search(sampledNum)
            expList.append(self.buffer.getItem(retrIndex))
            weightList.append(self.weights[retrIndex] /
                              self.sumTree.getAllSum())
            indexList.append(retrIndex)

        return np.asarray(expList), np.asarray(weightList), np.asarray(
            indexList)

    def getMaxPriority(self):
        if self.heap.size == 0:
            return sys.float_info.max
        return self.heap.p2w[1]
Exemplo n.º 17
0
 def test_insert(self):
     heap = Heap(lambda a, b: a <= b)
     sequence = [5, 9, 3, 4, 6, 2, 0, 8, 7, 1]
     min_items = [5, 5, 3, 3, 3, 2, 0, 0, 0, 0]
     self.assertRaises(IndexError, heap.peek)
     for index, (item, min_item) in enumerate(zip(sequence, min_items)):
         heap.insert(item)
         self.assertEqual(index + 1, len(heap))
         self.assertEqual(min_item, heap.peek())
Exemplo n.º 18
0
def main():
    """
    Entrypoint to our software
    """
    heap = Heap()
    if len(sys.argv) != 2:
        print('usage: python Driver.py <text_file>')
    else:
        heap.go(str(sys.argv[1]))
Exemplo n.º 19
0
def heapsort(A):
    H = Heap()
    n = len(A)
    for i in range(n):
        H.insert(A[i])
    k = n - 1
    for i in range(H._csize):
        A[k] = H.deletemax()
        k = k - 1
Exemplo n.º 20
0
 def test_extract(self):
     heap = Heap(lambda a, b: a <= b)
     sequence = [5, 9, 3, 4, 6, 2, 0, 8, 7, 1]
     self.assertRaises(IndexError, heap.extract)
     for item in sequence:
         heap.insert(item)
     for index in range(len(sequence)):
         self.assertEqual(index, heap.extract())
     self.assertRaises(IndexError, heap.extract)
Exemplo n.º 21
0
    def __init__(self, robot, map) -> None:
        self._rb = robot
        self._map = map.map

        self.last_goal_x = 0
        self.last_goal_y = 0
        self.path = []

        self.heap = Heap((self._map.map_size, self._map.map_size))
Exemplo n.º 22
0
 def __init__(self, maxSize, alpha=0.6, epsilon=0.000001):
     self.maxSize = maxSize
     self.buffer = Buffer(self.maxSize)
     self.sumTree = SumTree(self.maxSize)
     self.weights = {}
     self.alpha = 0.6
     self.curSize = 0
     self.epsilon = epsilon
     self.heap = Heap()
Exemplo n.º 23
0
def test_get_parent():
    """Test get_parent method."""
    from Heap import Heap
    hl = Heap()
    hl.hl.append(data[0])
    hl.hl.append(data[1])
    hl.hl.append(data[2])
    assert hl.hl[hl.get_parent(1)] == data[0]
    assert hl.hl[hl.get_parent(2)] == data[0]
Exemplo n.º 24
0
def heapSort(list):
    heap = Heap()  # Create a Heap

    # Add elements to the heap
    for v in list:
        heap.add(v)

    # Remove elements from the heap
    for i in range(len(list)):
        list[len(list) - 1 - i] = heap.remove()
Exemplo n.º 25
0
def heapSort(list):
    heap = Heap()  # Create a Heap

    # Add elements to the heap
    for v in list:
        heap.add(v)

    # Remove elements from the heap
    for i in range(len(list)):
        list[len(list) - 1 - i] = heap.remove()
Exemplo n.º 26
0
    def __init__(self, numNodes=0):

        # Call the constructor of the base class :
        Heap.__init__(self)

        # Initialize the indices of all vertices in the Graph to Infinity:
        self.indList = []

        for idx in range(numNodes):
            self.indList.append(np.Inf)
Exemplo n.º 27
0
def heap_sort(array):
    h = Heap()
    for i in range(len(array)):
        h.insert(array[i])

    sorted = []

    for i in range(len(h.heap_array)):
        sorted.append(h.extract_min())

    return sorted
Exemplo n.º 28
0
 def sort(self, data):
     print("Heapsort of size " + str(len(data)))
     if len(data) > 0:
         heap = Heap(data)
         #print("Heap ===> " + heap.printHeap())
         sortedData = []
         while heap.size > 0:
             sortedData.append(heap.removeMin())
         return sortedData
     else:
         return data
Exemplo n.º 29
0
def heap_sort(items, cmp_func):
    sorted_array = []
    if cmp_func is None:
        cmp_func = lambda parent, child: parent <= child

    heap = Heap(cmp_func)
    heap.build_heap(items)
    while heap.size > 0:
        sorted_array.append(heap.pop())

    return sorted_array
Exemplo n.º 30
0
 def sort(self, data):
     print("Heapsort of size "+ str(len(data)))
     if len(data) > 0:
         heap = Heap(data)
         #print("Heap ===> " + heap.printHeap())
         sortedData = []
         while heap.size > 0:
             sortedData.append(heap.removeMin())
         return sortedData
     else:
         return data
Exemplo n.º 31
0
    def __init__(self, src, dst, dtype, location, dimension):
        self.src = int(src)
        self.dst = int(dst)

        self.org_node = LoadData.load_org_node(location)
        self.org_path = LoadData.load_org_path(location, dimension)
        self.link_table = LoadData.load_linking_table(location)
        # print('org_node', self.org_node)
        # print('org_path', self.org_path)
        # print('self.link_table', self.link_table)

        self.heap = Heap(dtype)
        self.quadrant = self.__get_quadrant(self.src, self.dst)
    def KruskalMST_heap(self):
        V = len(self.node)
        result = []  # 存MST的每条边
        E = len(self.graph)
        i = 0  # 用来遍历原图中的每条边,但一般情况都遍历不完
        e = 0  # 用来判断当前最小生成树的边数是否已经等于V-1

        # 按照权重对每条边进行排序,如果不能改变给的图,那么就创建一个副本,内建函数sorted返回的是一个副本
        # self.graph = sorted(self.graph, key=lambda item: item[2])

        #初始化最小堆
        minHeap = Heap()
        for i in range(len(self.graph)):
            edge = self.graph[i]
            minHeap.array.append(minHeap.newMinHeapNode(v=i, dist=edge[2]))
            #newMinHeapNode方法返回一个list,包括节点id、节点key值
            #minHeap.array成员存储每个list,所以是二维list
            #所以初始时堆里的每个节点的key值都是无穷大
            minHeap.pos.append(i)

        minHeap.size = E
        minHeap.decreaseKey(0, minHeap.array[0][1])

        parent = []
        rank = []

        # 创建V个子树,都只包含一个节点
        for node in range(V):
            parent.append(node)
            rank.append(0)

        # MST的最终边数将为V-1
        while (e < V - 1):
            if i > len(self.graph) - 1:
                break

            # 选择权值最小的边,这里已经排好序
            edge = minHeap.extractMin()
            index = edge[0]
            dist = edge[1]
            minHeap.decreaseKey(index, dist)
            u, v, w = self.graph[index]
            i = i + 1
            x = self.find(parent, u)
            y = self.find(parent, v)

            # 如果没形成边,则记录下来这条边
            if x != y:
                # 不等于才代表没有环
                e = e + 1
                result.append(Edge(self.node[u], self.node[v], w))
                #result.append([u,v,w])
                self.union(parent, rank, u, v, x, y)
            # 否则就抛弃这条边

        return result
Exemplo n.º 33
0
def a_star(graph, heuristic, rows, columns):
    visited = list()
    heap = Heap(rows * columns, heuristic, rows, columns)
    pathFound = False
    depth = 0

    if (graph.getVertex(1)):
        # to_explore.append(graph.getVertex(1))
        heap.addElement(graph.getVertex(1))

        while not heap.isempty():
            depth += 1
            if depth % 500 == 0:
                print(depth)
            # current = to_explore.pop()
            current = heap.poll()
            # print(current.value, "--> ", end=" ")
            if current.value == rows * columns:
                pathFound = True
                break
            # print("current", current)
            current_children = current.edges

            for key, value in current_children.items():
                if key not in visited:
                    visited.append(key)
                    heap.addElement(graph.getVertex(key))

    if pathFound == True:
        print("Nodes explored", depth)
    else:
        print("no path found")
class MaxPQ(object):

    def __init__(self):
        self.items = Heap()

    def __str__(self):
        return str(self.items)

    def _print(self):
        self.items._print()

    def insert(self, item):
        self.items.insert(item)

    def max(self, item):
        self.items.items[1]

    def remove_max(self):
        self.items.remove_max()

    def is_empty(self):
        return self.items.size() == 0

    def size(self):
        return self.items.size()
Exemplo n.º 35
0
def encode_huffman():
    huffman = Heap()
    huffman.make_heap(freq_dict(file))
    huffman.merge_nodes()
    huffman.init_codes()
    encoded = huffman.encode_text(file)
    print(encoded)
    b = huffman.byte_array(encoded)
    #padded = huffman.pad_encoded_text(file)
    #print(padded)
    #b = huffman.byte_array(padded)

    with open("output.bin", "wb") as output:
        output.write(bytes(b))
Exemplo n.º 36
0
    def test_heap_property(self, heap = None):

        if heap == None:
            heap = Heap(self.arr3)
        
        for index in range(1, len(heap.array)):

            lIndex = heap.left(index)
            if lIndex < heap.size:
                self.assertGreaterEqual(heap.array[index], heap.array[lIndex])
            
            rIndex = heap.right(index)
            if rIndex < heap.size:
                self.assertGreaterEqual(heap.array[index], heap.array[rIndex])
Exemplo n.º 37
0
    def p_cores_centrality(self, p=None):
        
#        print 'computing node strength.'
#        strength_list = []         
#        for node, str in self.__strength().iteritems():
#            strength_list.append((node,str))

#        print 'sorting by node strength.'
#        strength_list.sort(snd_fst_cmp)
#        print 'splitting by node strength'
#        strength_list, per_strength = self.__split_by_float(strength_list)
#        
#        if strength_list == []:
#            return []
#        
#        p_cores = {}
#        last_core = []
#        last_strength = per_strength[0][0]
#        while len(per_strength) > 0:
#            node = per_strength[0][1].pop(0)
#            strength = per_strength[0][0]
#            if len(per_strength[0][1]) == 0:
#                per_strength.pop(0)
#            if strength != last_strength:
#                p_cores.append((last_strength, last_core))
#                last_strength = strength
#                last_core = [node]
#            else:
#                pass
 
        C_graph = copy.deepcopy(self.__graph.get_graph())
 
        print 'computing node strength min_queue.'   
        min_queue = Heap(snd_fst_cmp)
        strength = self.__strength()
        for node, stre in strength.iteritems():            
            min_queue.push((node,stre))
            if len(min_queue) % 1000 == 0:
                print 'nodes added to min_queue %d' % len(min_queue)  

            
        if len(min_queue) == 0:
            return []       
 
        print 'computing p-coreness per-se'
        core = {}
        while len(min_queue) > 0:          
            if len(min_queue) % 1000 == 0:
                print 'remaining %d nodes' % len(min_queue)  
            top,stren = min_queue.pop()
            core[top] = stren
            neighs = C_graph.neighbors(top)
            C_graph.delete_node(top)
            del strength[top]
            for v in neighs:
                min_queue.pop_item((v,strength[v]))
                strength[v] = max(stren, self.__node_strength(C_graph, v))
                min_queue.push((v,strength[v]))
        return core
Exemplo n.º 38
0
    def test__validate_that_list_is_heap(self):
        """
        Scenario:
        1. Create an object of Heap class
        2. Initialize the heap by the list with partially ordered elements according to max heap concept:
            https://en.wikipedia.org/wiki/Binary_heap#Heap_implementation
        3. Call validate_that_list_is_heap()

        Expected result: The list validated as heap
        """
        new_heap = Heap()
        new_heap.heap = [100, 92, 82, 48, 86, 52, 71, 44, 37, 50, 42, 13, 21, 1, 44, 25, 3, 5, 6, 8]

        actual_result = new_heap.validate_that_list_is_heap()

        self.assertEqual(True, actual_result)
Exemplo n.º 39
0
    def test__validate_that_list_is_heap__if_child_exceeds_parent__returns_False(self):
        """
        Scenario:
        1. Create an object of Heap class
        2. Initialize the heap by the list with INCORRECT placed first element according to max heap concept:
        https://en.wikipedia.org/wiki/Binary_heap#Heap_implementation
        3. Call validate_that_list_is_heap()

        Expected result: The list validated as NOT heap
        """
        new_heap = Heap()
        new_heap.heap = [91, 92, 82, 48, 86, 52, 71, 44, 37, 50, 42, 13, 21, 1, 44, 25, 3, 5, 6, 8]

        actual_result = new_heap.validate_that_list_is_heap()

        self.assertEqual(False, actual_result)
Exemplo n.º 40
0
def p107(network="p107.network"):
    network=open(network)
    network=[row.split(',') for row in network.read().split('\n')[:-1]]
    edges=Heap(0)
    counter=0
    for i in xrange(len(network)):
        if network[0][i]!='-':
            edges.add((int(network[0][i]),0,i))
    vertices=set([0])
    cost=0
    total_cost=0
    for i in xrange(len(network)):
        for j in xrange(i+1,len(network)):
            if network[i][j]!='-':
                total_cost+=int(network[i][j])
    while len(vertices)<len(network):
        edge=edges.removeMin()
        while edge[2] in vertices:
            edge=edges.removeMin()
        vertices.add(edge[2])
        cost+=edge[0]
        for i in xrange(len(network)):
            if network[edge[2]][i]!='-':
                edges.add((int(network[edge[2]][i]),edge[2],i))
    print total_cost-cost
Exemplo n.º 41
0
class PriorityQueue:
    def __init__(self):
        self.__heap = Heap()

    # Adds an element to this queue
    def enqueue(self, e):
        self.__heap.add(e)
    
    # Removes an element from this queue
    def dequeue(self):
        if self.getSize() == 0:
            return None
        else:
            return self.__heap.remove()
    
    # Return the size of the queue
    def getSize(self):
        return self.__heap.getSize()
Exemplo n.º 42
0
def test_compare_parent():
    """Test get_left method."""
    from Heap import Heap
    hl = Heap()
    hl.push(data[2])
    hl.push(data[1])
    hl.push(data[3])
    hl.compare_parent(0) 
    assert hl.hl == [data[3], data[1], data[2]]
Exemplo n.º 43
0
def getHuffmanTree(counts):
    # Create a heap to hold trees
    heap = Heap() # Defined in Listing 11.8
    for i in range(len(counts)):
        if counts[i] > 0:
            heap.add(Tree(Node(counts[i], chr(i)))) # A leaf node tree
    
    while heap.getSize() > 1:
        t1 = heap.remove() # Remove the smallest-weight tree
        t2 = heap.remove() # Remove the next smallest 
        heap.add(Tree(t1, t2)) # Combine two trees

    return heap.remove() # The final tree
Exemplo n.º 44
0
def test_pop():
    """Test pop method."""
    from Heap import Heap
    hl = Heap()
    hl.push(data[2])
    hl.push(data[1])
    hl.push(data[3])
    assert hl.pop() == data[2]
Exemplo n.º 45
0
def test_get_right():
    """Test get_left method."""
    from Heap import Heap
    hl = Heap()
    hl.push(data[0])
    hl.push(data[1])
    hl.push(data[2])
    assert hl.hl[hl.get_right(0)] == data[2]
Exemplo n.º 46
0
 def findKthLargest2(self, nums, k):
     from Heap import Heap
     heap = Heap()
     for num in nums:
         heap.insert(num)
     for _ in xrange(k - 1):
         heap.delete_max()
     return heap.delete_max()
Exemplo n.º 47
0
 def test_heap_basic_functions(self):
   heap = Heap(lambda x,y: x > y)
   self.assertTrue(heap.is_empty())
   self.assertEqual(len(heap),0)
   heap.push(5)
   self.assertEqual(len(heap),1)
   heap.push_list([3,8,1,4])
   self.assertEqual(len(heap),5)
Exemplo n.º 48
0
 def shortest_path_tree2(self, s, hint=None):
     """A Heap-based implementation of Dijkstra's algorithm
     based on Connelly Barnes's modification of David eppstein's
     code at
     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466
     """
     for v in self:
         v.dist = Inf
         
     queue = Heap([(0, s)])
     
     while len(queue) > 0:
         
         (cost, v) = queue.popmin()
         if v.dist < Inf:
             continue
         v.dist = cost
         
         for w, e in self[v].iteritems():
             if w.dist < Inf:
                 continue
             new = v.dist + e.length
             queue.push((new, w))
Exemplo n.º 49
0
    def __init__(self,start,goal,scale=1):
        super(AStar, self).__init__()
        #The open list
        self.OL_forward = Heap()
        self.OL_backward = Heap()

        self.scale = scale
        #The goal value
        self.start = start
        self.goal = goal
        
        #Setting up the open list with start state
        start_state = State(start, 0, None,self.goal,True,self.scale)
        self.OL_forward.insert(start_state)
        goal_state = State(goal, 0, None,self.start,False,self.scale)
        self.OL_backward.insert(goal_state)

        #The closed list
        self.CL = dict()
        self.CL_forward = dict()
        self.CL_backward = dict()
        
        self.log = []
        self.expand_count = 0
Exemplo n.º 50
0
    def __init__(self,start,goal,scale=1):
        super(AStar, self).__init__()
        #The open list
        self.OL = Heap()
        self.scale = scale
        #The goal value
        self.goal = goal
        
        #Setting up the open list with start state
        start_state = State(start, 0, None,self.goal,self.scale)
        self.OL.insert(start_state)

        #The closed list
        self.CL = dict()
        self.log = []
        self.expand_count = 0
        self.reincarnation_expand_count = 0
Exemplo n.º 51
0
 def heapSort(self,A):
     from Heap import Heap
     h = Heap(A)
     i = len(A)
     while i >= 2:
         j = h.heap[1]  
         h.heap [1] = h.heap[i]
         h.heap [i] = j
         h.heapsize = h.heapsize - 1
         h.maxHeapify(1)
         i = i-1
     return h.heap[1:len(h.heap)]
Exemplo n.º 52
0
 def find_path(self):
     node = self.__start
     self.__mOpenList = Heap(None, compare)
     self.__mOpenList.insert(node)
     while True:
         # pop the node which has the smallest f
         cur = self.__mOpenList.delete(0)
         if cur == None: # the heap is empty
             return False
         if cur.gridNode.isSameNode(self.__goal): # success
             self.__mClosedList.append(cur)
             return True
         self.__mClosedList.append(cur)
         candidates = self.get_successors(cur.gridNode)
         # check if the node in closed list or not
         for candidate in candidates:
             i = 0
             length = len(self.__mClosedList)
             while i<length:
                 if candidate.isSameNode(self.__mClosedList[i].gridNode):
                     break
                 i = i+1
             if i<length: # already in closed list, ignore it
                 continue
             # check if the node in open list or not
             j = 0
             length = len(self.__mOpenList.heap)
             while j<length:
                 if candidate.isSameNode(self.__mOpenList.heap[j].gridNode):
                     break
                 j = j+1
             if j<length: # already in open list,
                 new_pathNode = PathNode(cur, candidate, self.__goal)
                 if new_pathNode.g < self.__mOpenList.heap[j].g:
                     self.__mOpenList.delete(j)
                     self.__mOpenList.insert(new_pathNode)
             else:
                 new_pathNode = PathNode(cur, candidate, self.__goal)
                 self.__mOpenList.insert(new_pathNode)
Exemplo n.º 53
0
def dijkstra(d, root):
    """ Returns a dict of the dist from the root to all other nodes in d.
        Implemented using a heap.
    """
    heap = Heap()
    heap.insert(root, 0)
    final_dist = {}
    while len(final_dist) != len(d):
        n = heap.remove_min()
        if n.name not in final_dist:
            # minimum value in heap is the shortest path to that node
            # lock it down
            final_dist[n.name] = n.value
            for child, dist in d[n.name].iteritems():
                total_dist = dist + n.value
                heap.insert(child, total_dist)

    return final_dist
def merge_lists(lists):
    ''' merge len(lists) sorted linked lists, and return the result linked list
    '''
    for each_list in lists:        
        each_list.append_node(ListNode(sys.maxint))
    min_heap = Heap()
    result_list = LinkList()
    curr_nodes = [each_list.head for each_list in lists]
    curr_datas = [node.data for node in curr_nodes]
    # build the heap according to curr_datas
    min_heap.build_heap('min', curr_datas)
    # min_heap.heap[0] == maxint means all the lists go to end, only then, stop the while loop
    while min_heap.heap[0] != sys.maxint:
        # extract min node
        curr_min = min_heap.extract_node()
        # append to result
        result_list.append_node(ListNode(curr_min))
        min_index = curr_datas.index(curr_min)
        curr_nodes[min_index] = curr_nodes[min_index].next
        curr_datas[min_index] = curr_nodes[min_index].data
        # insert the extracted node's next's data, and re-heapify
        min_heap.add_node(curr_datas[min_index])
    return result_list
Exemplo n.º 55
0
# -*- coding: utf-8 -*-

"""
App:
"""

from Heap import Heap

heap = Heap()

heap.insert(12)
heap.insert(-3)
heap.insert(23)
heap.insert(4)

heap.heapsort()


from Heap import Heap;

heap = Heap();
        
heap.insert(10);
heap.insert(-20);
heap.insert(0);
heap.insert(2);
heap.insert(15);
heap.insert(156);
        
heap.heapsort();

Exemplo n.º 57
0
from Heap import Heap

x=Heap()

for i in xrange(20,0,-1):
    x.add(i)
    
x.getSelf()
Exemplo n.º 58
0
 def __init__(self,A):
     self._heap = Heap(A)
Exemplo n.º 59
0
 def __init__(self):
     self.__heap = Heap()