Example #1
0
# -*- coding: utf-8 -*-
__author__ = 'xiaoxiaoming'

import os
from Heap import Heap

fs = []
min_heap = Heap(type="min", sort_key=lambda x: int(x[0]))
out = open("out.log", "w")
for i, filename in enumerate(os.listdir("../logs")):
    fo = open(os.path.join("../logs", filename))
    fs.append(fo)
    min_heap.insert((fo.readline().rstrip(), i))

while True:
    data, i = min_heap.get_top()
    out.write(data)
    out.write("\n")
    line = fs[i].readline().rstrip()
    if line:
        min_heap.update_top((line, i))
    else:
        min_heap.remove_top()
        fs[i].close()
        if min_heap.index == -1: break

out.close()
Example #2
0
def HeapwithEntriesInserted():
    #
    # read the input information from the default input text file into an
    # entry list, entry_list
    #
    entry_list = []
    f = open('inFile1.txt', 'r')
    for line in f.readlines():
        entry_list.append(line.rstrip("\n").split())
    f.close()

    #
    # initiating a heap object h
    #
    h = Heap()

    #
    # Do something here to build the heap
    #

    for elements in entry_list:
        key = elements[0]
        data = elements[1]
        h.Insert(Hnode(key, data))

    #---------------------Print as the example on the homework sheet --------
    #                       will be adapted with the input
    #
    print("Heap size=", h.getSize(), "The highest priority is ",
          h.getHighestPriority())
    print("pre-order traversal:")
    h.printHeapPreOrder(h.getRoot())

    print("deleteMin")
    h.removeMin()

    print("deleteMin")
    h.removeMin()

    print("deleteMin")
    h.removeMin()

    print("deleteMin")
    h.removeMin()

    print("deleteMin")
    h.removeMin()

    print("insert 35, resume")
    h.Insert(Hnode(35, "resume"))

    print("insert 15, second")
    h.Insert(Hnode(15, "second"))

    print("insert 20, fourth")
    h.Insert(Hnode(20, "fourth"))

    print("Heap size=", h.getSize(), "The highest priority is ",
          h.getHighestPriority())
    print("pre-order traversal:")
    h.printHeapPreOrder(h.getRoot())

    print("deleteMin")
    h.removeMin()

    print("insert 40, nineth")
    h.Insert(Hnode(40, "nineth"))
Example #3
0
import re
from Heap import Heap
from Hnode import Hnode

#####
#
# insert not ordered
#
#####
h = Heap()
print("insert 10, resume")
h.Insert(Hnode(10, "resume"))

print("insert 15, second")
h.Insert(Hnode(15, "second"))

print("insert 20, fourth")
h.Insert(Hnode(20, "fourth"))

print("insert 25, fourth")
h.Insert(Hnode(25, "ourth"))

print("insert 30, yoooth")
h.Insert(Hnode(30, "yoooth"))

h.printHeapPreOrder(h.getRoot())
print()

leafs = h.findLeafs(h.getRoot())
for leaf in leafs:
    print("Leaf is ", leaf.key, leaf.item, " depth is ", leaf.depth)
 def setUp(self):
     self.heap = Heap([])
Example #5
0
from Heap import Heap

newHeap = Heap()

newHeap.insert(12)
newHeap.insert(-3)
newHeap.insert(23)
newHeap.insert(4)
newHeap.insert(100)

newHeap.displayHeap()
Example #6
0
 avl.insert_node(n4)
 avl.insert_node(n5)
 avl.insert_node(n6)
 """
 avl.insert(143,12,time.time())
 avl.insert(18,4,time.time())
 avl.insert(1432,512,time.time())
 avl.insert(173,112,time.time())
 avl.insert(1,1,time.time())
 avl.insert(3,120,time.time())
 """
 pickle.dump(avl,open("lj.txt","w"))
 avl_read = pickle.load(open("lj.txt","r"))
 avl_read.delete(173)
 plot_tree(avl_read)
 heap = Heap()
 """
 avl_read.get_node(143).hotnessCount = 7
 avl_read.get_node(18).hotnessCount = 9
 avl_read.get_node(1432).hotnessCount = 688
 avl_read.get_node(1).hotnessCount = 1
 avl_read.get_node(3).hotnessCount = 277
 """
 n1.hotnessCount = 7
 n2.hotnessCount = 9
 n3.hotnessCount = 688
 n4.hotnessCount = 1
 n5.hotnessCount = 277
 """
 heap.add(avl_read.get_node(143))
 heap.add(avl_read.get_node(18))
 def test_heap_sort(self):
     self.heap = Heap([1, 3, 5, 6, 3, 2, 1, 2, 5, 6, 6, 17, 19, 10])
     self.heap.build_heap()
     self.assertEqual(self.heap.heap_sort(),
                      [19, 17, 10, 6, 6, 6, 5, 5, 3, 3, 2, 2, 1, 1])
def yenKSP(graph, source, sink, K):

    #A is a list containing the shortest path A[0] to A[K -1]
    A = []
    #B is a list containing potential k'th shortest path
    B = Heap("min", lambda x,y: calcPathCost(x) > calcPathCost(y))

    # Determine the shortest path from source to sink
    A.append(dijkstra(graph,source,sink))
    print("k: 0")
    print("     Shortest path: " + '->'.join([node.key for node in A[0]]) + ", cost = " + str(calcPathCost(A[0])))

    for k in range(1, K):
        print("k: " + str(k))
        # The spur node ranges from the first node to the next to last last node in the previous k-shortest path
        for i in range(len(A[k - 1]) - 1):

            #spur node is retrieved from the previous k-shortest path, k - 1
            spurNode = A[k-1][i]

            print("     Spur Node: " + spurNode.key)

            # The sequence of nodes from the source to the spur node of the previous k-shortest path
            rootPath = A[k-1][0:i+1]
            print("     Root path: " + '->'.join([node.key for node in rootPath]) + ", cost = " + str(calcPathCost(rootPath)))

            for path in A:
                if rootPath == path[0:i+1]:
                    # Remove the links that are part of the previous shortest paths which share the same root path.
                    if path[i].adjList[path[i+1].key]['availability'] == True:
                        path[i].adjList[path[i+1].key]['availability'] = False
                        print("         Removing edge: " + path[i].key + "->" + path[i].adjList[path[i+1].key]['k'].key)

            for rootPathNode in rootPath: #remove each node in the rootpath excep spur node
                if rootPathNode != spurNode:
                    rootPathNode.availability = False

            #Calculate the spur path from the spur node to the sink
            spurPath = dijkstra(graph, spurNode, sink)
            if(spurPath != None):
                print("     Spur path: " + '->'.join([node.key for node in spurPath]) + ", cost = " + str(calcPathCost(spurPath)))
                spurPath = spurPath[1:]
                totalPath = rootPath + spurPath
                print("     Total path: " + '->'.join([node.key for node in totalPath]) + ", cost = " + str(calcPathCost(totalPath)))
                if not totalPath in B.heap:
                    print("     Inserting Total Path to heap")
                    B.insert(totalPath)
                else:
                    print("     Path already exists")
            else:
                print("     No Spur path found")

            print()
            #Resstore edge and nodes that were remove from the graph
            for vertex in graph:
                vertex.availability = True
                for key, adjVertex in vertex.adjList.items():
                    adjVertex['availability'] = True

        if len(B.heap) == 0:
        # This handles the case of there being no spur paths, or no spur paths left.
        # This could happen if the spur paths have already been exhausted (added to A),
        # or there are no spur paths at all - such as when both the source and sink vertices
        # line alone a "dead end"
            break

        if len(B.heap) >= K - k + 1:
            print("     Heap has more than required k path: " + str(len(B.heap)))
            for _ in range(0, K - k):
                A.append(B.extract())
            break

        A.append(B.extract())
        print("     Shortest path: " + '->'.join([node.key for node in A[k]]) + ", cost = " + str(calcPathCost(A[k])))

    return A
Example #9
0
from Heap import Heap

g = Heap([1, 3, 2, 4, 1])
h = Heap()
print(g.N)
while (not g.isempty()):
    print(g.deletemin(), end=" ")

print()
Example #10
0
 def __init__(self):
     self.queue = Heap()
Example #11
0
 def test_init(self):
     heap1 = Heap(self.arr1)
     heap2 = Heap(self.arr2)
Example #12
0
def main():
    h1 = Heap()
    h2 = Heap()
Example #13
0
 def addVertex(vertex):
     Graph.addVertex(vertex)
     queues.add(Heap())
Example #14
0
from Heap import Heap

H = Heap()

H.add(10)
H.add(15)
H.add(17)
H.add(20)
H.add(8)
H.add(9)

print(H.peek() == 8)
H.poll()
print(H.peek() == 9)
H.poll()
print(H.peek() == 10)
H.poll()
print(H.peek() == 15)
Example #15
0
 def __init__(self):
     self.__heap = Heap()
Example #16
0
	def __init__(self, arr):
		heap = Heap(len(arr))
		heap.create_heap(arr)
		heap.print_heap(0, 1)
Example #17
0
from Heap import Heap

x=Heap()

for i in xrange(20,0,-1):
    x.add(i)
    
x.getSelf()
Example #18
0
    def __init__(self, frequency):
        if type(frequency) == Node:
            # if a node is given it is assumed to be the huffman tree
            self.huffmanTree = frequency
            # the __depth function is used to create the huffman table with
            # all the values codes
            self.table = {
            }  # the table with every code of every input from de frequency
            self.__depth(self.huffmanTree, '')
            self.__size = len(
                self.table)  # the ammount of entries in the frequency dic
        else:
            # if the frequency has a string, a dictionary is created by counting
            # the number of times that each character appears in the string
            # and assigning it to a dictionary input
            if type(frequency) == str:
                self.frequency = {
                    val: frequency.count(val)
                    for val in frequency
                }
            # if the frequency has an array, an auxiliary function is called to
            # create the dictionary, see '__freqCountArray' for more info
            if type(frequency) == np.ndarray:
                self.frequency = self.__freqCountArray(frequency)

            if type(frequency) == dict:
                self.frequency = frequency
            heap = Heap()
            self.huffmanTree = []  # the binary huffman tree
            self.table = {
            }  # the table with every code of every input from de frequency
            self.__size = len(
                self.frequency)  # the ammount of entries in the frequency dic

            # the frequency must be a dictionary
            if type(self.frequency) == dict:
                # prepares the heap with initial values
                # this is used so every value in the heap
                # will already have a node inside it
                for i in self.frequency:
                    # the heap will use the first value as a key, and the
                    # second value as input for balancing it
                    # the third is optional and will be used to store the
                    # huffman tree
                    # everyting must be inside a tuple: (key, value, node)
                    heap.push(
                        (i, self.frequency[i], Node((i, self.frequency[i]))))
                # the operation keeps going until the heap has only one value
                # this single value will contain the huffman tree inside its third
                # element
                while len(heap) > 1:
                    # the heap is a min heap, so the first removed value
                    # will always be smaller than the second one
                    # this way, the left child will have a smaller value
                    # than the right child
                    (left, right) = heap.pop(), heap.pop()
                    nodeLeft = left[2]  # assign the node
                    nodeRight = right[2]  # assign the node
                    # finally a new heap entry is created, with the sum of the
                    # values from the left and right child
                    # and its node will be a partent from the left node and the right node
                    # assigned above
                    heap.push(('', left[1] + right[1],
                               Node(('', left[1] + right[1]), nodeLeft,
                                    nodeRight)))
                # after finishing the task, the heap can be emptied
                # and the huffman tree taken from the third value of the last tuple
                self.huffmanTree = heap.pop()[2]
                # the __depth function is used to create the huffman table with
                # all the values codes
                self.__depth(self.huffmanTree, '')
 def test_build_heap2(self):
     self.heap = Heap([1, 2, 3, 4, 5, 6])
     self.heap.build_heap()
     self.assertEqual(self.heap._array, [6, 5, 3, 4, 2, 1])
Example #20
0
    def BipartiteMST(self):
        # 存每个节点的key值
        edges = {}
        left_data = self.leftData
        right_data = self.rightData

        num_left = len(left_data)
        num_right = len(right_data)

        key_left = []
        key_right = []

        parent_left = []
        parent_right = []

        # 建立最小堆
        minHeap_left = Heap()
        minHeap_right = Heap()

        # 初始化左节点三个数据结构
        for v in range(num_left):
            parent_left.append(-1)  #初始时,每个节点的父节点是-1
            key_left.append(float('inf'))  #初始时,每个节点的key值都是无穷大
            minHeap_left.array.append(
                minHeap_left.newMinHeapNode(v, key_left[v]))
            minHeap_left.pos.append(v)

        # 初始化右节点三个数据结构
        for v in range(num_right):
            parent_right.append(-1)  #初始时,每个节点的父节点是-1
            key_right.append(float('inf'))  #初始时,每个节点的key值都是无穷大
            minHeap_right.array.append(
                minHeap_right.newMinHeapNode(v, key_right[v]))
            minHeap_right.pos.append(v)

        minHeap_left.pos[0] = 0  #不懂这句,本来pos的0索引元素就是0啊
        key_left[0] = 0  #让0节点作为第一个被挑选的节点
        minHeap_left.decreaseKey(0, key_left[0])
        #把堆中0位置的key值变成key[0],函数内部重构堆

        minHeap_right.pos[0] = 0
        #key_right[0] = 0
        minHeap_right.decreaseKey(0, key_right[0])

        # 初始化堆的大小为V即节点个数
        minHeap_left.size = num_left
        minHeap_right.size = num_right

        label = 'left'
        while minHeap_left.isEmpty(
        ) == False | minHeap_right.isEmpty() == False:
            # 抽取最小堆中key值最小的节点
            if label == 'left':
                newHeapNode = minHeap_left.extractMin()
                u = newHeapNode[0]

                for i in range(minHeap_right.size):
                    id = minHeap_right.array[i][0]
                    dist = max(1 / 42, left_data[u].dtw_dist(right_data[id]))
                    if dist < key_right[id]:
                        key_right[id] = dist
                        parent_right[id] = u

                        # 也更新最小堆中节点的key值,重构
                        minHeap_right.decreaseKey(id, key_right[id])
                        edges[(u, id)] = dist

                label = 'right'
            else:
                newHeapNode = minHeap_right.extractMin()
                v = newHeapNode[0]

                for i in range(minHeap_left.size):
                    id = minHeap_left.array[i][0]
                    dist = max(1 / 42, right_data[v].dtw_dist(left_data[id]))
                    if dist < key_left[id]:
                        key_left[id] = dist
                        parent_left[id] = v

                        # 也更新最小堆中节点的key值,重构
                        minHeap_left.decreaseKey(id, key_left[id])

                        edges[(id, v)] = dist
                label = 'left'

        edgePairs = []
        for i in range(1, num_left):
            edgePairs.append((self.partitionId,Edge(right_data[parent_left[i]].getId(),left_data[i].getId(),\
                                                     edges[(i,parent_left[i])])))

        for j in range(0, num_right):
            edgePairs.append((self.partitionId,Edge(left_data[parent_right[j]].getId(),right_data[j].getId(),\
                                                    edges[(parent_right[j],j)])))

        return edgePairs
 def test_min_heap_sort(self):
     self.heap = Heap([1, 3, 5, 6, 3, 2, 1, 2, 5, 6, 6, 17, 19, 10])
     self.heap.build_heap(False)
     self.assertEqual(self.heap.heap_sort(False),
                      [1, 1, 2, 2, 3, 3, 5, 5, 6, 6, 6, 10, 17, 19])
Example #22
0
from algorithms import GetMedian, AddElement
from Heap import Heap

lowHeap = Heap([])
highHeap = Heap([])
strOut = ""
for i, line in enumerate(open("input.txt", "r")):
    if i > 0:
        AddElement(lowHeap, highHeap, int(line))
        med = GetMedian(lowHeap, highHeap)
        for i in range(len(med)):
            strOut += str(med[i])
            if i != len(med) - 1:
                strOut += " "
        strOut += "\n"

out = open("output.txt", "w")
out.write(strOut)
out.close()
 def init_heap(self):
     self.heap = Heap([1, 2, 3, 4, 5])
Example #24
0
    def singleSourceToDest(self, G, src, dest):
        """
		Priority Queue object using minheap DS
		"""
        PQ = Heap(1)
        """
		Preparing source item object to keep on PQ
		"""
        s = Item(src, 0)
        PQ.insert(s)
        """
		dist array where dist[i] contains shortest distance to ith vertex from source s
		"""
        dist = []
        """
		Initially none of the vertices are visited and are at a distance of -1 from source
		"""
        for vertex in G.vertices:
            dist.insert(vertex, -1)
        """
		src to src distance is 0
		"""
        dist[src] = 0

        path = {}

        while (PQ.isEmpty() == False):

            v = PQ.deleteMin()
            """
			reached destination hence print path and return distance
			"""
            if (v.item == dest):
                print path
                return dist[v.item]
            """
			computes new distance for the adjacent vertices with respect to current vertex and updates if it is less than old distance from s
			"""
            adjVertices = G.getAdjVerices(v)

            for adjVertex in adjVertices:
                edgLen = G.edges[v.item].get(adjVertex)

                if (edgLen != "None"):
                    newDist = dist[v.item] + edgLen
                else:
                    newDist = -1

                adjVertex = int(adjVertex)
                """
				If this vertex was not visited till now from source and can be reached from current vertex now
					Update distance and insert item into priority queue with new distance as priority
				Else If	New distance is less than old distance. 
					Update distance and priority of adjVertex to new distance on min Heap
				"""
                if (dist[adjVertex] == -1 and newDist != -1):
                    dist[adjVertex] = newDist
                    w = Item(adjVertex, newDist)
                    path[adjVertex] = v.item
                    PQ.insert(w)
                elif (dist[adjVertex] > newDist):
                    dist[adjVertex] = newDist
                    path[adjVertex] = v.item
                    PQ.updatePriority(adjVertex, newDist)
        """
		Destination cannot be reached. Hence return -1
		"""
        return -1
 def __init__(self):
     self.items = Heap()
    def dijkstra(self, i, j, i_, j_):
        res = list()
        vist = list()

        destinationNode = j_ * len(self.board[0]) + i_
        startingNode = j * len(self.board[0]) + i

        visited = [False] * len(self.graph)

        ptr = startingNode

        heap = Heap()
        heap.insert(self.graph[ptr])
        self.graph[ptr].h = self.heuristic2(i, j, i_, j_)
        self.graph[ptr].f = self.graph[ptr].h
        self.graph[ptr].g = 0

        while (heap.size != 0):
            ptr = heap.delete().vnum

            if (ptr == destinationNode):
                break

            visited[ptr] = True
            temp = list()

            if (ptr == destinationNode):
                res.append(destinationNode)
                break

            pt = self.graph[ptr].adjLists

            while (pt != None):
                if (pt.vnum == destinationNode):
                    break

                temp.append(pt.vnum)

                x = pt.vnum % len(self.board)
                y = pt.vnum / len(self.board)
                self.graph[pt.vnum].h = self.heuristic2(x, y, i_, j_)
                self.graph[pt.vnum].g = min(self.graph[pt.vnum].g,
                                            self.graph[ptr].g + pt.weight)

                self.graph[
                    pt.vnum].f = self.graph[pt.vnum].h + self.graph[pt.vnum].g

                if (visited[pt.vnum]):
                    pt = pt.next
                    continue

                visited[pt.vnum] = True
                heap.insert(self.graph[pt.vnum])

                pt = pt.next

            if (pt != None and pt.vnum == destinationNode):
                break
            vist.append(temp)

        self.graph[destinationNode].f = 0
        self.graph[destinationNode].h = 0

        #BACKTRACKING

        ptr = destinationNode
        visited = [False] * len(self.graph)
        visited[ptr] = True

        while (ptr != startingNode):
            res.insert(0, ptr)
            pt = self.graph[ptr].adjLists
            minPtr = pt

            while (pt != None):
                if (visited[pt.vnum]):
                    pt = pt.next
                    continue

                visited[pt.vnum] = True

                if (self.graph[minPtr.vnum].f > self.graph[pt.vnum].f):
                    minPtr = pt

                pt = pt.next

            ptr = minPtr.vnum

        res.insert(0, startingNode)
        return (res, vist)
Example #27
0
    d = (w, h)

    resized = cv2.resize(image, d, interpolation=cv2.INTER_AREA)

    (h_resized, w_resized, d_resized) = resized.shape

    image_copy = resized.copy()
    image_copy = cv2.cvtColor(image_copy, cv2.COLOR_RGB2GRAY)

    #first operations
    node = Node()
    node.setFrequencePixels(image_copy, h_resized, w_resized)
    tmp = node.returnArrayNode()

    #here we construct txhe heap minimum bottom_up
    heap = Heap(tmp)
    S = heap.returnHeapMinimum()

    #build the tree of heap Max
    huff = Huffman(S)
    R = huff.returnHuff()

    #build the dictionary
    D = huff.goThroughTree(R)

    #codification of the picture
    T, index = huff.compressOp(image_copy, w_resized, h_resized, D)

    #writing the codification in a file
    file = open('test.txt', 'w')
    for i in range(index):
Example #28
0
    print('C-3PO ha sido eliminado correctamente')
else:
    print('C-3PO no ha sido eliminado')
print()

#Punto 6
x = busqueda(arbol, 'Dar Vader')
if x is not None:
    x.info = 'Darth Vader'
print('Darth Vader ha sido modificado')
print()

#2 Heap

#Punto 1, 2 y 3
cola = Heap(10)
names = [['MARK XL', 'Reparar'], ['MARK L', 'Reparar'],
         ['MARK XX', 'Producir'], ['MARK MCC', 'Reparar'],
         ['MARK CLV', 'Producir'], ['MARK CMC', 'Reparar'],
         ['MARK CXX', 'Producir'], ['MARK MMXL', 'Producir']]

for i in range(0, 7):
    arribo(cola, names[i], randint(1, 3))

#Punto 4
for i in range(0, 3):
    print(atencion(cola))

arribo(cola, ['MARK XLV', 'Reparar'], 3)
arribo(cola, ['(MARK XXL,', 'Producir'], 2)
arribo(cola, ['MARK III', 'Reparar'], 1)
Example #29
0
# -*- coding: utf-8 -*-
__author__ = 'xiaoxiaoming'

from Heap import Heap

a = [0, 6, 3, 4, 0, 9, 2, 7, 5, -2, 8, 1, 6, 10]
max_heap = Heap(a)
max_heap.sort()
print(a)
 def __init__(self, percentile=0.5):
     self.min_heap = Heap(type="min")
     self.max_heap = Heap(type="max")
     self.count = 0
     self.percentile = percentile