def polar_angle(p0, point_list): '''sort a sequence <p1, p2, ... , pn> of n points according to their polar angles with respect to a given origin point p0. ''' v0 = vector((p0[0] + 1, p0[1]), p0) # The polar angle of v0 is 0 vector_list = [vector(p, p0) for p in point_list] angle_0 = [] # list of vectors whose polar angles are 0 angle_pi = [] # list of vectors whose polar angles are pi angle_0_pi = [ ] # list of vectors whose polar angles are larger than 0 and smaller than pi angle_pi_2pi = [ ] # list of vectors whose polar angles are larger than pi and smaller than 2pi for v in vector_list: if v == v0: if v.x > 0: angle_0.append(v) elif v.x < 0: angle_pi.append(v) elif v < v0: angle_pi_2pi.append(v) elif v > v0: angle_0_pi.append(v) heap_0_pi = MaxHeap(angle_0_pi) heap_pi_2pi = MaxHeap(angle_pi_2pi) heap_0_pi.heapsort() heap_pi_2pi.heapsort() return [(v.x, v.y) for v in (angle_0 + heap_0_pi + angle_pi + heap_pi_2pi)]
def test(self): # test data ob = MaxHeap() ob.insert(10) self.assertEqual(ob.peek(), 10, msg="Max Element is not matched") ob.insert(5) self.assertEqual(ob.peek(), 10, msg="Max Element is not matched") ob.insert(6) self.assertEqual(ob.peek(), 10, msg="Max Element is not matched") ob.insert(3) self.assertEqual(ob.peek(), 10, msg="Max Element is not matched") ob.insert(8) self.assertEqual(ob.peek(), 10, msg="Max Element is not matched") ob.insert(20) self.assertEqual(ob.peek(), 20, msg="Max Element is not matched") ob.pop() self.assertEqual(ob.peek(), 10, msg="Max Element is not matched") ob.pop() self.assertEqual(ob.peek(), 8, msg="Max Element is not matched") ob.pop() self.assertEqual(ob.peek(), 6, msg="Max Element is not matched") ob.pop() self.assertEqual(ob.peek(), 5, msg="Max Element is not matched") ob.pop() self.assertEqual(ob.peek(), 3, msg="Max Element is not matched") ob.pop() self.assertEqual(ob.peek(), None, msg="Max Element is not matched")
def any_segments_intersect(S): '''This algorithm takes as input a set S of n line segments, returning the boolean value TRUE if any pair of segments in S intersects, and FALSE otherwise.''' T = rb_tree() segment_list = [] point_list = [] for s in S: segment_list.append(segment(s)) for s in segment_list: point_list.append(point([s[0][0], 0, s[0][1]], s)) point_list.append(point([s[1][0], 1, s[1][1]], s)) heap_point = MaxHeap(point_list) heap_point.heapsort() for p in heap_point: if p[1] == 0: s = p.segment T.insert(s) a = T.above(s) b = T.below(s) if (a != None and segments_intersect(a[0], a[1], s[0], s[1])) or (b != None and segments_intersect(b[0], b[1], s[0], s[1])): return True if p[1] == 1: s = p.segment a = T.above(s) b = T.below(s) # print( a) # print( b) # print( type(a)) # print( type(b)) if a != None and b != None and segments_intersect(a[0], a[1], b[0], b[1]): return True T.delete(s) return False
def heapSort1(nums): n = len(nums) maxheap = MaxHeap() for i in xrange(n): maxheap.insert(nums[i]) for i in xrange(n - 1, -1, -1): nums[i] = maxheap.extractMax()
def k_largest(arr, k): h = MaxHeap() for item in arr: h.insert(item) for i in range(k): largest = h.extract() print(largest) return
def test_insert_and_del_max_from_algs_book(self): heap = MaxHeap(['E', 'P', 'I', 'S', 'N', 'H', 'G', 'R', 'O', 'A']) heap.insert('T') self.assertEqual(heap.del_max(), 'T') self.assertEqual(heap.del_max(), 'S') self.assertEqual(heap.del_max(), 'R') self.assertEqual(heap.del_max(), 'P')
def heap_sort(arr, n): """ 使用已经实现的最大堆来实现排序 """ heap = MaxHeap() for i in range(n): heap.insert(arr[i]) for j in reversed(range(n)): arr[j] = heap.remove()
def y_sort(S): Y = [] for p in S: Y.append((p[1], p[0])) YY = MaxHeap(Y) YY.heapsort() Y = [] for i in range(0, len(YY)): Y.append((YY[i][1], YY[i][0])) return Y
def kSmallestElement(arr, k): maxH = MaxHeap(arr[:k]) maxH.convertToHeap() for x in arr[k:]: max_ele = maxH.getMax() if max_ele > x: maxH.replaceMax(x) return maxH.getMax()
def model_template(client, tokens, scoring_func, size=1000): doc_ids = get_related_docs(client, tokens) client.cache_docs(doc_ids) scored_docs = MaxHeap(size) scoring_start_time = time.time() print(f" score_docs={len(doc_ids)}(documents)") for _id in doc_ids: score = scoring_func(client, _id, tokens) scored_docs.push((score, _id)) print(f" elapsed_t={time_used(scoring_start_time)}") return scored_docs.top()
def test_insert_and_del_max(self): heap = MaxHeap([1, 2]) heap.insert(4) heap.insert(3) self.assertEqual(heap.size, 4) self.assertEqual(heap.del_max(), 4) self.assertEqual(heap.del_max(), 3) self.assertEqual(heap.del_max(), 2) self.assertEqual(heap.del_max(), 1)
def heap_sort(lst): """ This functions is sorting a list according to heap sort in O(nlog(n)) :param lst: The list to sort :return: The sorted list """ size = len(lst) heap = MaxHeap(lst) sorted_lst = [] for i in range(size): sorted_lst.append(heap.extract_max()) return sorted_lst[::-1]
def heap_sort(direction=True, nums=None): """ :param direction: True means sort from small to large, False means sort from large to small :param nums: heap data :return: sorted data """ # different direction correspond different heap type if direction: heap = MaxHeap(nums) else: heap = MinHeap(nums) return heap.sort()
def heapFullTest(): """ Various tests for Heap class, using both MinHeaps and MaxHeaps, including sorting and random operations. """ print("Testing MinHeap: sorting") for i in range(1, 21): if heapRandomSort(250, True): print "Test", i, "successful" else: print "Test", i, "failed" print("\nTesting MaxHeap: sorting") for i in range(1, 21): if heapRandomSort(250, False): print "Test", i, "successful" else: print "Test", i, "failed" print("\nTesting MinHeap: general") for i in range(1, 21): if heapRandomTest(250, True): print "Test", i, "successful" else: print "Test", i, "failed" print("\nTesting MaxHeap: general") for i in range(1, 21): if heapRandomTest(250, False): print "Test", i, "successful" else: print "Test", i, "failed" print("\nTesting MinHeap: other operations") ar = [1, 4, 501, -200, 32, 7, 65, -1, 20000, -34, 17] min_heap = MinHeap() min_heap.createMinHeap(ar) print min_heap.extractMin() print min_heap.extractMin() print min_heap.extractMin() max_heap = MaxHeap() max_heap.createMaxHeap(ar) print max_heap.extractMax() print max_heap.extractMax() print max_heap.extractMax() print "Max: ar", max( ar), "min_heap", min_heap.maximum(), "max_heap", max_heap.maximum() print "Min: ar", min( ar), "min_heap", min_heap.minimum(), "max_heap", max_heap.minimum()
def printKBestCandidates(self, k=None): if k is None: k = len(self._candidates) from heap import MaxHeap c: Candidate # for c in self._candidates: # print(c) h = MaxHeap(len(self._candidates)) for c in self._candidates: h.insert(c) result_number = len( self._candidates) if len(self._candidates) < k else k for i in range(result_number): print(h.extractMax())
def HeapSort(val): #define variables arr=[] n = len(val) #build maxheap mh = MaxHeap(val) #for every element in list do swap for i in range(n-1,-1,-1): mh._data[i],mh._data[0] = mh._data[0],mh._data[i] #append array after sort arr.insert(0,mh._data[-1]) #remove maxheap eat each step del mh._data[-1] #until last element in array call max_heapify mh.max_heapify(0,i) return arr
def test(): counts = [(1, 'one'), (3, 'fish'), (1, 'two'), (2, 'red'), (7, 'the'), (4, 'ball'), (1, 'who')] word_heap = MaxHeap(counts) print(word_heap.to_list() == [(7, 'the'), (3, 'fish'), ( 4, 'ball'), (1, 'one'), (2, 'red'), (1, 'two'), (1, 'who')]) print(word_heap.size == len(counts)) print(word_heap.root() == (7, 'the')) print(word_heap.peek(3) == [(7, 'the'), (3, 'fish'), (4, 'ball')]) print(word_heap.remove_max() == (7, 'the')) print(word_heap.root() == (4, 'ball')) word_heap.push((8, 'bank')) print(word_heap.root() == (8, 'bank')) print( word_heap.take(4) == [(8, 'bank'), (4, 'ball'), (3, 'fish'), (2, 'red')])
def get_closest_points(k, my_point, points): ''' Complex = O(N + ) time Complex = O(N) space ''' distances = {} s = MaxHeap([]) for point in points: distance = get_distance(point, my_point) if distance not in distances: distances[distance] = [point] s.push(distance) else: distances[distance].append(point) ret_points = [] while k: ret_points.append(distances[s.pop()]) k -= 1 return ret_points
def any_disks_intersect(S): """ This algorithm takes as input a set S of n disks represented by its center point and radius, returning the boolean value TRUE if any pair of disks in S intersects, and FALSE otherwise. :param S: :return: """ T = rb_tree() point_list = [] disk_list = [] for s in S: disk_list.append(disk(s)) for s in disk_list: center_point = s[0] radius = s[1] x = center_point[0] y = center_point[1] point_list.append(point([x - radius, 0, y], s)) point_list.append(point([x + radius, 1, y], s)) heap_point = MaxHeap(point_list) heap_point.heapsort() print(heap_point) for p in heap_point: if p[1] == 0: s = p.disk T.insert(s) a = T.above(s) b = T.below(s) print("insert: ", a, b) if (a is not None and disks_intersect(a, s)) or (b is not None and disks_intersect(b, s)): return True if p[1] == 1: s = p.disk a = T.above(s) b = T.below(s) if a is not None and b is not None and disks_intersect(a, b): return True T.delete(s) return False
def C2W3(): """Median Maintain""" from heap import MinHeap, MaxHeap MinHeap = MinHeap() MaxHeap = MaxHeap() medians = [] heaplow, heaphigh = [], [] lowmax, highmin = float('-inf'), float('inf') with open('Median.txt') as file: for line in file: item = int(line) lenlow, lenhigh = len(heaplow), len(heaphigh) while True: if lenlow > lenhigh: if item >= lowmax: MinHeap.add(heaphigh, item) highmin = heaphigh[0] break if item < lowmax: returnitem = MaxHeap.popadd(heaplow, item) MinHeap.add(heaphigh, returnitem) lowmax = heaplow[0] highmin = heaphigh[0] break if lenlow <= lenhigh: if item <= highmin: MaxHeap.add(heaplow, item) lowmax = heaplow[0] break if item > highmin: returnitem = MinHeap.popadd(heaphigh, item) MaxHeap.add(heaplow, returnitem) lowmax = heaplow[0] highmin = heaphigh[0] break medians.append(lowmax) print('item', item, 'lowmax', lowmax, 'highmin', highmin) return sum(medians), len(medians)
def three_points_colinear(points_list): '''An algorithm to determine whether any three points in a set of n points are colinear''' n = len(points_list) vectors_list = [] for i in range(n): for j in range(i + 1, n): vectors_list.append(vector(points_list[i], points_list[j], i, j)) v0 = vector((1, 0), (0, 0)) heap_vectors = MaxHeap(vectors_list) heap_vectors.heapsort() status = [False] * n v = heap_vectors[0] status[v.p1_index] = True status[v.p2_index] = True stack = [] stack.append(v.p1_index) stack.append(v.p2_index) for i in range(1, len(heap_vectors)): v = heap_vectors[i] if v == heap_vectors[i - 1]: if status[v.p1_index]: return True elif status[v.p2_index]: return True else: status[v.p1_index] = True status[v.p2_index] = True stack.append(v.p1_index) stack.append(v.p2_index) else: print(len(stack)) print(stack) for i in range(len(stack)): status[stack.pop()] = False stack.append(v.p1_index) stack.append(v.p2_index) return False
def heap_sort_2(arr, n): heap = MaxHeap() heap.heapify(arr) for j in reversed(range(n)): arr[j] = heap.remove()
def __init__(self, maxsize=None): self.maxsize = maxsize self._maxheap = MaxHeap(maxsize)
def test_1(): heap = MaxHeap(*'abcdef', n=3) assert heap.height == 3
def x_sort(S): X = MaxHeap(S) X.heapsort() return X
def test_is_empty(self): heap = MaxHeap() self.assertTrue(heap.is_empty()) heap = MaxHeap([1, 2]) self.assertFalse(heap.is_empty())
def setUp(self): self.heap = MaxHeap()
def test_size_after_insertion(self): heap = MaxHeap([1, 2]) heap.insert(3) heap.insert(4) self.assertEqual(heap.size, 4)
def __init__(self): self.upper = MinHeap() self.lower = MaxHeap()
def max_heap_test(): h = MaxHeap() heap_test(h) return