def huffman(str):
    freqdict = frequency(str)
    pq = PriorityQueue()

    for char in freqdict:  # NOT for char in STRING!!
        t = BinaryTree(char)
        key = freqdict[char]
        pq.add((key, t))

    while pq.getSize() > 1:
        u = pq.delMin()
        v = pq.delMin()
        t = BinaryTree(u[0] + v[0])
        t.insertLeft(u[1])  # inserts left subtree T1
        t.insertRight(v[1])  # inserts right subtree T2
        pq.add((u[0] + v[0],
                t))  # inserts T into PQ with key f1 + f2 (from u and v tuples)

    result = pq.delMin()  # tuple of (freq, T)
    return result[1]  # returns the final tree, T
def dijkstra(aGraph,start):
	pq = PriorityQueue()
	start.setDistance(0)
	pq.buildHeap([(v.getDistance(),v) for v in aGraph])
	while not pq.isEmpty():
		currentVert = pq.delMin()
		for nextVert in currentVert.getConnections():
			newDist = currentVert.getDistance() + currentVert.getWeight(nextVert)
			if newDist < nextVert.getDistance():
				nextVert.getDistance( newDist )
				nextVert.setPred(currentVert)
				pq.decreaseKey(nextVert,newdist)
Beispiel #3
0
def dijkstra(aGraph, start):
    pq = PriorityQueue()
    start.setDistance(0)
    pq.buildHeap([(v.getDistance(), v)
                  for v in aGraph])  # builds heap from list
    while not pq.isEmpty():
        currentVert = pq.delMin()  # start with the lowest distance item first
        for nextVert in currentVert.getConnections(
        ):  # for each connected node...
            newDist = currentVert.getDistance() + currentVert.getWeight(
                nextVert)
            if newDist < nextVert.getDistance():
                nextVert.setDistance(newDist)
                nextVert.setPred(currentVert)
                pq.decreaseKey(
                    nextVert,
                    newDist)  # is this like bubbling up the priority?