class MinPQ:
	def __init__(self,items = None):
		self._minHeap = MinHeap()
		self.count = 0

		if isinstance(items,collections.Iterable):
			#if items have been supplied build a MinPQ from those items. 
			for elm in items:
				self.enqueue(elm)
			

	def __iter__(self):
		return self

	def next(self):
		if not self.isEmpty():
			return self.dequeue()
		else:
			raise StopIteration()

	def enqueue(self,n):
		self._minHeap.append(n)
		self.count += 1

	def dequeue(self):
		j = self._minHeap.delMin()
		self.count -= 1
		return j

	def isEmpty(self):
		return self.count == 0

	def show(self):
		print(self._minHeap)
	def __init__(self,items = None):
		self._minHeap = MinHeap()
		self.count = 0

		if isinstance(items,collections.Iterable):
			#if items have been supplied build a MinPQ from those items. 
			for elm in items:
				self.enqueue(elm)
Beispiel #3
0
def nearestNeighbor(trainingSet, testRow, classCol, k):
    minHeap = MinHeap(len(trainingSet.index))
    for row in trainingSet.iterrows():
        dropRow = row[1].drop(classCol)
        dist = findDistance(dropRow, testRow, classCol)
        minHeap.insert((row, dist))
    minHeap.minHeap()

    # Determine class by k neighbor voting
    votes = {}
    for i in range(k):
        minVal = minHeap.remove()
        if minVal[0][1][classCol] in votes:
            votes[minVal[0][1][classCol]] += 1
        else:
            votes[minVal[0][1][classCol]] = 1

    maxVotes = 0
    predictedClass = ""
    for key in votes:
        if votes[key] > maxVotes:
            maxVotes = votes[key]
            predictedClass = key

    return 0 if (predictedClass == testRow[1][classCol]) else 1
def ksort(inputlist, k ):
    indx =1
    heap = MinHeap()
    res = []
    heap.insertKey(inputlist[0])
    while len(heap.heap)>0:
        for i in range(k+1):
            if indx < len(inputlist):
                heap.insertKey(inputlist[indx])
                indx+=1
        minValue = heap.extractMin()
        res.append(minValue)
           
    return res 
    def huffman_tree(self, frequencyMap):
        #--------------------------------------------
        #build a priority queue - a min Heap of all characters and their frequencies, the min heap will sort the data
        minh = MinHeap(self.priorityCallback)
        for char, freq in frequencyMap.items():
            minh.push(Node(char, freq))

        #--------------------------------------------
        #Merge sets of nodes in heap to create a huffman tree, Repeat until only one node remains in the priority queue.

        while (minh.size() > 1):
            #extract two minimum frequency node from min heap
            node1 = minh.pop()
            node2 = minh.pop()
            """
      Create a new internal node with a frequency equal to the sum of the two nodes frequencies. Set the first extracted node as its left child and the other extracted node as its right child. Add this node to the min heap. 
      """

            #create newNode
            newNode = Node()

            #set frequency equal to the sum of the two nodes frequencies
            nPriority = (node1.get_priority() if node1 else
                         0) + (node2.get_priority() if node2 else 0)

            if (nPriority > 0):
                newNode.set_priority(nPriority)

                #Set the first extracted node as the left child
                newNode.set_left_child(node1)

                #Set the other extracted node as the right child
                newNode.set_right_child(node2)

                #add newNode to the min heap.
                minh.push(newNode)

        return minh
Beispiel #6
0
def Dijkstra(graph, start):# pylint: disable=invalid-name
    """ Main implementation using Priority Queue"""
    priorityqueue = MinHeap()
    priorityqueue.insertKey(start)

    distance = [-1 for i in range(graph.num_of_nodes)]
    path = [-1 for i in range(graph.num_of_nodes)]
    while not priorityqueue.empty():
        v = priorityqueue.extractMin() # pylint: disable=invalid-name
        print(graph.graph.items(),"...",v)
        for adj, weight in graph.graph.get(v):
            d = distance[v] + weight # pylint: disable=invalid-name
            if distance[adj] == -1:
                distance[adj] = d
                priorityqueue.insertKey(adj)
                priorityqueue.decreaseKey(adj, d)
            elif distance[adj] > d:
                distance[adj] = d
                priorityqueue.decreaseKey(adj, d)
            
            path[adj] = v

    return distance, path
Beispiel #7
0
 def test_add_AddsElemToHeap(self):
     minHeap = MinHeap()
     minHeap.add(3)
     firstItem = minHeap.heap[0]
     self.assertEqual(firstItem, 3)
Beispiel #8
0
 def test_convertArrayToHeap_MaintainsHeapOrder(self):
     minHeap = MinHeap()
     arr = [3, 9, 12, 7, 1]
     expectedHeap = [1, 3, 12, 9, 7]
     res = minHeap.convertArrayToHeap(arr)
     self.assertListEqual(expectedHeap, res)
    def dijkstraFindPath(self,
                         startPoint,
                         endPoint,
                         pointsInPath,
                         checkLineIntersection=False,
                         searchRange=DEFAULT_SEARCH_RANGE):
        # pre-calculate distances in a search range cube
        self.gridScanDistances = []
        for k in range(-searchRange, searchRange + 1):
            grid2dDistances = []
            for i in range(-searchRange, searchRange + 1):
                tmp = []
                for j in range(-searchRange, searchRange + 1):
                    tmp.append((i**2 + (j * LENGTH / WIDTH)**2 +
                                (k * LENGTH / HEIGHT)**2)**0.5)
                grid2dDistances.append(tmp)
            self.gridScanDistances.append(grid2dDistances)

        self.grid[startPoint[2]][startPoint[1]][startPoint[0]].setDistance(0)
        pq = MinHeap()
        pq.insert(
            self.grid[startPoint[2]][startPoint[1]][startPoint[0]], self.grid[
                startPoint[2]][startPoint[1]][startPoint[0]].getDistance())

        count = 0
        while pq.counter != 0:
            currGridPoint = pq.del_min()
            if currGridPoint.getDistance(
            ) > LARGE_DISTANCE:  # these are the points that cannot be reached from the start point
                print("points covered: " + str(count))
                print("Destination point cannot be reached")
                raise Exception()
                break
            currGridPoint.visit()
            currX = currGridPoint.x
            currY = currGridPoint.y
            currZ = currGridPoint.z

            if (
                    currX, currY
            ) == endPoint:  # if we've reached the endpoint, then its okay to stop
                break

            # go through all the neighbours of the current point
            for k in range(-searchRange, searchRange + 1):
                z = k + currZ
                for i in range(-searchRange, searchRange + 1):
                    y = i + currY
                    for j in range(-searchRange, searchRange + 1):
                        x = j + currX

                        if x < 0 or x >= WIDTH or y < 0 or y >= LENGTH or z < 0 or z >= HEIGHT:  # check if out of bounds
                            continue

                        # check if point has been visited and whether it is accessible or not
                        currPoint = self.grid[z][y][x]
                        if currPoint.beenVisited(
                        ) or not currPoint.isAccessible():
                            continue
                        if checkLineIntersection:  # option that adds a shitton of time to the algo
                            line = LineString([[currX, currY], [x, y]])
                            continueFlag = False
                            for noFlyZone in self.noFlyZones:
                                if line.intersects(noFlyZone):
                                    continueFlag = True
                                    break
                            if continueFlag:
                                continue

                        oldDist = currPoint.getDistance()
                        newDist = currGridPoint.getDistance(
                        ) + self.gridScanDistances[k + searchRange][
                            i + searchRange][j + searchRange]
                        if newDist < oldDist:
                            currPoint.setDistance(newDist)
                            pq.insert(currPoint, currPoint.getDistance())
                            currPoint.setParent(currGridPoint)
            count = count + 1

        # check if the endpoint has actually been visited (probs not necessary but why not)
        endGridPoint = self.grid[endPoint[2]][endPoint[1]][endPoint[0]]
        if endGridPoint.getDistance() > LARGE_DISTANCE:
            print("no path could be found")
            raise Exception()
            return

        # now find the shortest path by going up the tree
        startGridPoint = self.grid[startPoint[2]][startPoint[1]][startPoint[0]]
        tempPath = []
        while endGridPoint != startGridPoint:
            if endGridPoint == None:
                print("no path could be found between following two points: ",
                      end="")
                print(startPoint, end="")
                print(endPoint)
                raise Exception()
                return
            tempPath.append((endGridPoint.x, endGridPoint.y, endGridPoint.z))
            endGridPoint = endGridPoint.getParent()
        tempPath.append((startGridPoint.x, startGridPoint.y, endGridPoint.z))

        totalDistance = 0
        # reverse them, append onto list then calculate distance
        for x in range(len(tempPath) - 2, -1, -1):
            totalDistance = totalDistance + (
                abs(tempPath[x + 1][0] - tempPath[x][0])**2 +
                abs(tempPath[x + 1][1] - tempPath[x][1])**2 +
                abs(tempPath[x + 1][2] - tempPath[x][2])**2)**0.5
            pointsInPath.append(tempPath[x])

        self.gridReset()

        return totalDistance
Beispiel #10
0
# Add, edit, or remove tests in this file.
# Treat it as your playground!

from minHeap import MinHeap
import unittest

test1 = MinHeap([2, 3, 1])

test2 = MinHeap([1, 2, 3, 4, 5, 6, 7, 8, 9])

test3 = MinHeap([48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41])
test3.insert(76)
test3.remove()
test3.remove()
test3.insert(87)

test3a = MinHeap([[1, 48], [1, 12], [1, 24], [1, 7], [1, 8], [1, -5], [1, 24],
                  [1, 39], [1, 24], [1, 56], [1, 2], [1, 6], [1, 8], [1, 41]])
test3a.insert([1, 76])
test3a.remove()
test3a.remove()
test3a.insert([1, 9])
test3a.insert([1, 10])
test3a.insert([1, 87])
test3a.insert([1, -87])
test3a.insert([1, 49])

test4 = MinHeap(
    [-4, 5, 10, 8, -10, -6, -4, -2, -5, 3, 5, -4, -5, -1, 1, 6, -7, -6, -7, 8])

test5 = MinHeap(
Beispiel #11
0
#!/user/bin/env python

from minHeap import MinHeap

mHeap = MinHeap()
a = [3, 5, 6, 63, 47, 2, 46, 7]
print(a)
mHeap.min_heapify(a)
b = mHeap.heap_sort()
print(b)

maxHeap = MinHeap()
c = [23, 123, 422, 112, 42, 12, 23]
d = [x * -1 for x in c]
maxHeap.min_heapify(d)
e = [x * -1 for x in maxHeap.heap_sort()]
print(e)
Beispiel #12
0
def Dijkstra(graph, start):  # pylint: disable=invalid-name
    """ Main implementation using Priority Queue"""
    priorityqueue = MinHeap()
    priorityqueue.insertKey(start)

    distance = [-1 for i in range(graph.num_of_nodes)]
    path = [-1 for i in range(graph.num_of_nodes)]
    while not priorityqueue.empty():
        v = priorityqueue.extractMin()  # pylint: disable=invalid-name
        print(graph.graph.items(), "...", v)
        for adj, weight in graph.graph.get(v):
            d = distance[v] + weight  # pylint: disable=invalid-name
            if distance[adj] == -1:
                distance[adj] = d
                priorityqueue.insertKey(adj)
                priorityqueue.decreaseKey(adj, d)
            elif distance[adj] > d:
                distance[adj] = d
                priorityqueue.decreaseKey(adj, d)

            path[adj] = v

    return distance, path