def heap_sort(int_array): minheap = MinHeap("value") for x in int_array: minheap.push(NodeForPrimitiveDataTypes(x)) return minheap.get_sorted_list()
def findMaxK(vals, k): minHeap = MinHeap(k) for n in vals: if minHeap.get_size() < k: minHeap.push(n) elif minHeap.peek() < n: minHeap.pop() minHeap.push(n) while minHeap.get_size() > 0: print(minHeap.pop())
def dijkstra (source_vertex, vertices, edges): minheap = MinHeap("dist") for vertex in vertices: vertex.parent = vertex vertex.dist = 999999 minheap.push(vertex) minheap.update_key( minheap.find_index(vertices[0]), 0 ) while not minheap.is_empty(): vertex = minheap.pop() print(vertex.id, vertex.parent.id, vertex.dist) for dest_vertex, weight in edges[vertex]: if dest_vertex.dist > vertex.dist + weight: dest_vertex.parent = vertex minheap.update_key( minheap.find_index(dest_vertex), vertex.dist + weight )
def MST_prim2(self): #최종적으로 만들어질 MST mst = Graph() mst.add_vertex(self.vertex_num) #TV={} : MST 정점의 집합, 시작 노드부터 하나씩 채워나간다 TV = set() #w_list : 각 정점의 w 값을 담아두기 위한 배열 w_list = [None for _ in range(self.vertex_num)] #min heap에 w와 from을 가진 정점을 담아둔다 #heap 초기화 : w->inf, from->None h = MinHeap() for i in range(1, self.vertex_num): w_list[i] = math.inf h.push(Element(i, math.inf, None)) #시작 노드인 0은 w->0, from->None w_list[0] = 0 h.push(Element(0, 0, None)) while not h.is_empty(): #가중치가 가장 작은 에지 (from, v) : w #정보를 가진 정점 Element v v = h.pop() #TV에 정점을 추가 TV.add(v.v) #TE에 에지 추가 if v._from != None: mst.insert_edge(v.v, v._from, v.w) #TV에 정점이 추가되면 인접 정점 중 #트리 밖에 있는 정점에 대해 업데이트 시도 #u는 새로 추가된 정점 v에 인접한 정점 노드 u = self.adjacency_list[v.v] while u: #u가 트리 밖의 정점이고 #기존 w 값보다 w(u, v)이 작다면 업데이트 if u.vertex not in TV and u.weight < w_list[u.vertex]: #w_list 업데이트 w_list[u.vertex] = u.weight h.decrease_weight(Element(u.vertex, u.weight, v.v)) u = u.link return mst
def dijkstra(self, start): seen = set() heap = MinHeap() heap.push(start, start.val) seen.add(start) while not heap.is_empty(): top, priority = heap.pop() for name, edge_dist in top.neighbors.items(): tmp_distance = edge_dist + priority neighbor = self.nodes[name] if tmp_distance < neighbor.val: neighbor.parent = top neighbor.val = tmp_distance if neighbor in seen: heap.update_priority(neighbor, neighbor.val) else: heap.push(neighbor, neighbor.val)
def algorithm(P: NPuzzleInstance, name='ASTAR'): begin = time.now() open_heap = MinHeap() open_heap.push( P.initial_state, P.initial_state.get_total_cost() if name == 'ASTAR' else P.initial_state.greedy_value) cost_so_far = {P.initial_state: 0} father_of = {P.initial_state: None} while not open_heap.is_empty(): # print('heap size -> ' + str(len(open_heap.elements)), end='\r', flush=True) P.current_state = open_heap.pop() if P.is_solved(): P.spent_time = time.now() - begin solution = [] curr = P.current_state while curr: solution.append(curr) curr = father_of[curr] P.build_solution(list(reversed(solution))) return P for neighbor in P.neighbors(): if neighbor not in cost_so_far.keys( ) or P.current_state.greedy_value < cost_so_far[neighbor]: cost_so_far[neighbor] = P.current_state.greedy_value open_heap.push( neighbor, neighbor.get_total_cost() if name == 'ASTAR' else neighbor.greedy_value) father_of[neighbor] = State( P.current_state.matrix, P.current_state.greedy_value, P.current_state.heuristic_value if name == 'ASTAR' else 0) return None
class PriorityQueue(object): def __init__(self): self._heap = MinHeap() self._num_inserted = 0 def _gen_order(self): self._num_inserted += 1 return self._num_inserted def insert(self, prioritized_item): prioritized_item._order = self. _gen_order() self._heap.push(prioritized_item) def pop(self): return self._heap.pop() def peek(self): return self._heap.peek() def __str__(self): s = [] [s.append(str(item)) for item in self._heap._list] return "".join(s)
def a_star_search(P: NPuzzleInstance, parents=[]): open_heap = MinHeap() open_heap.push(P.initial_state, P.initial_state.get_total_cost()) cost_so_far = { P.initial_state: 0 } father_of = { P.initial_state: None } while not open_heap.is_empty(): print('\theap size -> ' + str(len(open_heap.elements)), end='\r', flush=True) P.current_state = open_heap.pop() if P.is_solved(): solution = [] curr = P.current_state while father_of[curr]: solution.append(curr) curr = father_of[curr] solution.append(curr) return list(reversed(solution)) for neighbor in P.neighbors(): new_cost = P.current_state.greedy_value if neighbor not in cost_so_far.keys() or new_cost < cost_so_far[neighbor]: cost_so_far[neighbor] = new_cost open_heap.push(neighbor, neighbor.get_total_cost()) father_of[neighbor] = State( P.current_state.matrix, P.current_state.greedy_value, P.current_state.heuristic_value ) return None
class RunningMedian: def __init__(self): self.left_max_heap = MaxHeap() self.right_min_heap = MinHeap() def stream_element(self, a): left_len, right_len = self.left_max_heap.get_length( ), self.right_min_heap.get_length() if left_len == right_len: self.left_max_heap.push(a) return if left_len > right_len: peek = self.left_max_heap.peek() if a >= peek: self.right_min_heap.push(a) else: popped = self.left_max_heap.pop() self.left_max_heap.push(a) self.right_min_heap.push(popped) return if left_len < right_len: peek = self.right_min_heap.peek() if a <= peek: self.left_max_heap.push(a) else: popped = self.right_min_heap.pop() self.right_min_heap.push(a) self.left_max_heap.push(popped) return def get_current_median(self): left_len, right_len = self.left_max_heap.get_length( ), self.right_min_heap.get_length() if left_len == 0 and right_len == 0: raise ("No element is streamed") if left_len > right_len: median = self.left_max_heap.peek() return median if right_len > left_len: median = self.right_min_heap.peek() return median if left_len == right_len: median = (self.left_max_heap.peek() + self.right_min_heap.peek()) / 2.0 return median
# As long as we don't need to carry the numbers that summed to # our desired number, we should be fine. from min_heap import MinHeap import random import statistics # Coerce to int so numbers match better data = [int(random.randint(-5, 20)) for _ in range(20_000)] # Pick a number at random from data number_to_match = random.choice(data) # Make a min heap with this data mn = MinHeap() mn.push(data) def count(tree, index, number_to_match, running_totals): """Count how many series equal the number to match.""" if index is None: return 0 if tree.get_value(index) is None: # Avoid index out of range return 0 # Get the value value = tree.get_value(index) # Append a zero the the running totals
def test_push(self): init = [2, 7, 9, 5] heap = MinHeap(init) heap.push(1) self.assertEqual(heap.values, [1, 2, 9, 7, 5])