def get_path(self, grid, start, target): open_list = [start] closed = set() path = [] start.h(manhattan_dist(start, target)) while target.g() > open_list[0].f(): self.total += 1 current = heap_pop(open_list) closed.add(current) current.color(7) for neighbor in grid.neighbors(current): if neighbor.search() < self.counter: neighbor.g(sys.maxsize) neighbor.search(self.counter) if current.g() + self.cost(neighbor) < neighbor.g(): neighbor.g(current.g() + self.cost(neighbor)) neighbor.parent = current if neighbor in open_list: open_list.remove(neighbor) heapify(open_list) if neighbor.h() == sys.maxsize: neighbor.h(manhattan_dist(neighbor, target)) heap_push(open_list, neighbor) for node in closed: node.h(target.g() - node.g()) if len(open_list) == 0: return () current = target while current != start: path.append(current) current = current.parent path.reverse() return tuple(path)
def test_unordered_list_2(self): """ ┌──10 │ ┌──8 │ └──2 7 │ ┌──9 │ │ └──3 │ ┌──1 └──1 └──11 heapify() ┌──7 │ ┌──10 │ └──2 8 │ ┌──9 │ │ └──3 │ ┌──1 └──1 └──11 """ ls = [7, 3, 8, 1, 9, 2, 10, 11, 1] heapify(ls, 0) self.assertEqual(ls, [8, 3, 10, 1, 9, 2, 7, 11, 1])
def testHeapify(self): size = 100 array = [random.randrange(size) for i in range(size)] copy = sorted(array) heapify(array) self.checkHeapProperty(array) for elem in copy: self.assertEqual(heappop(array), elem)
def using_max_heap(ar, k): l = len(ar) build_heap(ar) for i in range(k): ar[0], ar[l - i - 1] = ar[l - i - 1], ar[0] heapify(ar, 0, l - i) return ar[-k:]
def pop_max(self): assert len(self.list) >= 1, 'priority queue underflow' max = self.list[0] self.list[0] = self.list[-1] del self.list[-1] heapify(self.list, 0) return max
def get_shortest_path(start, end, vlist): # distances使用字典的方式保存每一个顶点到start点的距离 distances = {} # 从start到某点的最优路径的前一个结点 # eg:start->B->D->E,则previous[E]=D,previous[D]=B,等等 previous = {} # 用来保存图中所有顶点的到start点的距离的优先队列 # 这个距离不一定是最短距离 nodes = [] for vertex in vlist: if vertex == start: distances[vertex] = 0 # 将start点的距离初始化为0 heap.heappush(nodes, [0, vertex]) # nodes.append([0,vertex]) elif vertex in g.neighboringVertices(start): distances[vertex] = length(start, vertex) # 把与star点相连的结点距离start点的距离初始化为对应的道路长度 heap.heappush(nodes, [length(start, vertex), vertex]) # nodes.append([length(start, vertex), vertex]) previous[vertex] = start else: distances[vertex] = 9999 # 把与start点不直接连接的结点距离start的距离初始化为9999 heap.heappush(nodes, [9999, vertex]) # nodes.append([9999, vertex]) previous[vertex] = None shortest_path = [1] lenPath = 0 while nodes: smallest = heap.heappop(nodes)[1] # 取出队列中最小距离的结点 # smallest = nodes.pop()[1] if smallest == end: shortest_path = [] lenPath = distances[smallest] temp = smallest #print('previous[temp]:',temp) while (temp != start) : shortest_path.append(temp) temp = previous[temp] shortest_path.append(temp) # 将start点也加入到shortest_path中 if distances[smallest] == 9999: # 所有点不可达 break # 遍历与smallest相连的结点,更新其与结点的距离、前继节点 for neighbor in g.neighboringVertices(smallest): dis = distances[smallest] + length(smallest, neighbor.getLabel()) if dis < distances[neighbor.getLabel()]: distances[neighbor.getLabel()] = dis previous[neighbor.getLabel()] = smallest # 更新与smallest相连的结点的前继节点 for node in nodes: if node[1] == neighbor.getLabel(): node[0] = dis # 更新与smallest相连的结点到start的距离 break heap.heapify(nodes) return shortest_path, lenPath
def kthSmallest(collection, k): '''Return Kth smallest element in collection for valid k >= 1''' A = collection[:k] heap.buildHeap(A) for i in xrange(k, len(collection)): if collection[i] < A[0]: A[0] = collection[i] heap.heapify(A, 0, k) return A[0]
def testHeappushpop(self): size = 100 array = [random.randrange(size) for i in range(size)] copy = sorted(array) heapify(array) self.checkHeapProperty(array) for i in range(100): elem = random.randrange(size) minimum = min(array + [elem]) self.assertEqual(heappushpop(array, elem), minimum) self.assertEqual(len(array), size) self.checkHeapProperty(array)
def test_already_max_heap(self): """ ┌──1 3 └──2 heapify() ┌──1 3 └──2 """ ls = [3, 2, 1] heapify(ls, 0) self.assertEqual(ls, [3, 2, 1])
def test_unordered_list_negative(self): """ ┌── 0 -1 └──-2 └──-3 heapify() ┌──-1 0 └──-2 └──-3 """ ls = [-1, -2, 0, -3] heapify(ls, 0) self.assertEqual(ls, [0, -2, -1, -3])
def heap_sort(list, inc=True): #implementation of heap sort list = heap.build_heap(list, inc) for i in range(len(list) - 1, 0, -1): list[0], list[i] = list[i], list[0] list[:i] = heap.heapify(list[:i], 0, inc) return list
def test_unordered_list(self): """ ┌──3 2 └──1 └──0 heapify() ┌──2 3 └──1 └──0 """ ls = [2, 1, 3, 0] heapify(ls, 0) self.assertEqual(ls, [3, 1, 2, 0])
def get_shortest_path(start, end, vlist): distances = {} previous = {} nodes = [] for vertex in vlist: if vertex == start: distances[vertex] = 0 heap.heappush(nodes, [0, vertex]) elif vertex in h.neighboringVertices(start): distances[vertex] = length2(start, vertex) heap.heappush(nodes, [length2(start, vertex), vertex]) previous[vertex] = start else: distances[vertex] = inf heap.heappush(nodes, [inf, vertex]) previous[vertex] = None shortest_path = [1] lenPath = 0 while nodes: smallest = heap.heappop(nodes)[1] # smallest = nodes.pop()[1] if smallest == end: shortest_path = [] lenPath = distances[smallest] temp = smallest while (temp != start): shortest_path.append(temp) temp = previous[temp] shortest_path.append(temp) if distances[smallest] == inf: break for neighbor in h.neighboringVertices(smallest): dis = distances[smallest] + length2(smallest, neighbor.getLabel()) if dis < distances[neighbor.getLabel()]: distances[neighbor.getLabel()] = dis previous[neighbor.getLabel()] = smallest for node in nodes: if node[1] == neighbor.getLabel(): node[0] = dis break heap.heapify(nodes) return shortest_path, lenPath
def assign(data): for a in data: if a[0] == "diplomatic": a[0] = 7500 + random.randint(1, 1000) elif a[0] == "private": a[0] = 6000 + random.randint(1, 1000) elif a[0] == "international": a[0] = 4500 + random.randint(1, 1000) elif a[0] == "domestic": a[0] = 3000 + random.randint(1, 1000) elif a[0] == "cargo": a[0] = 1500 + random.randint(1, 1000) heap.heapify(data)
def test_heapify(): print("#test_heapify") A = [1] heap.heapify(A, 0) print("Heapify length 1:", A == [1]) A = [2, 1] heap.heapify(A, 0) print("Heapify two out of order:", A == [1, 2]) A = [1, 2] heap.heapify(A, 0) print("Heapify two in order:", A == [1, 2]) A = [5, 4, 3, 2, 1] print("A: ", A) heap.heapify(A, 1) print("Heapify 1:", A == [5, 1, 3, 2, 4]) A = [5, 1, 3, 2, 4] heap.heapify(A, 0) print("Heapify 0:", A == [1, 2, 3, 5, 4])
def sortGraph(graph): indegree = {node: 0 for node in graph} for c in graph: for neighbor in graph[c]: indegree[neighbor] += 1 q = [node for node in graph if indegree[node] == 0] heapify(q) tpOrder = '' while q: cur = heappop(q) tpOrder = tpOrder + cur for nc in graph[cur]: indegree[nc] = indegree[nc] - 1 if indegree[nc] == 0: heappush(tpOrder, nc) if len(tpOrder) == len(graph): return True return False
def test_heapify(): print("#test_heapify") A = [1] heap.heapify(A, 0) print("Heapify length 1:", A == [1]) A = [2, 1] heap.heapify(A, 0) print("Heapify two out of order:", A == [1, 2]) A = [1, 2] heap.heapify(A, 0) print("Heapify two in order:", A == [1, 2]) A = [1, 4, 3, 5, 2] heap.heapify(A, 1) print("Heapify five needing swap:", A == [1, 2, 3, 5, 4]) A = [1, 8, 3, 9, 2, 10, 11, 12, 13, 7, 6] heap.heapify(A, 1) print("Heapify five needing recursive swap:", A == [1, 2, 3, 9, 6, 10, 11, 12, 13, 7, 8]) A = [1, 4, 3, 5, 2] heap.heapify(A, 1, 4) print("Heapify five with limit number:", A == [1, 4, 3, 5, 2])
def test_empty_list(self): ls = [] heapify(ls, 0) self.assertEqual(ls, [])
def test_insert(self): arr = [5, 3, 1, 2, 4] heapify(arr) insert(arr, 0) self.assertEqual(arr[0], 0, 'new head of min-heap should be 0')
def test_extract_index(self): arr = [5, 3, 1, 2, 4] heapify(arr) actual = extract_index(arr, 0) self.assertEqual(actual, 1, 'should pop the correct min') self.assertTrue(arr[0] != 1, 'new heap should miss the old min')
def test_heapify(self): arr = [5, 3, 1, 2, 4] heapify(arr) self.assertEqual(arr[0], 1, 'head of min-heap should be smallest value')