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
class CaixaBanco: def __init__(self, nome_banco: str): self.fila_prioridade = MaxHeap() self.nome_banco = nome_banco def adiciona_cliente(self, cliente: Cliente): ordem_de_prioridade = 3 if cliente.idade >= 80 else ( 2 if cliente.idade >= 60 or cliente.necessidades_especiais else 1) nova_priodade = PrioridadeCliente(cliente, ordem_de_prioridade) self.fila_prioridade.insere(nova_priodade) def proximo_cliente(self) -> Cliente: return self.fila_prioridade.retira_max() @property def tem_cliente(self): return len(self) > 0 def __str__(self): return f"Banco: {self.nome_banco} Fila: {self.fila_prioridade}" def __repr__(self): return str(self) def __len__(self): return len(self.fila_prioridade.arr_heap) - 1
class CaixaBanco: def __init__(self, nome_banco: str): self.fila_prioridade = MaxHeap() self.nome_banco = nome_banco def adiciona_cliente(self, cliente: Cliente): if cliente.idade > 80: prioridade = 3 p_cliente = PrioridadeCliente(cliente, prioridade) elif (cliente.idade > 60 and cliente.idade <= 80) or cliente.necessidades_especiais == True: prioridade = 2 p_cliente = PrioridadeCliente(cliente, prioridade) else: prioridade = 1 p_cliente = PrioridadeCliente(cliente, prioridade) self.fila_prioridade.insere(p_cliente) pass def proximo_cliente(self) -> Cliente: return print(f"Retirado: {self.fila_prioridade.retira_max()}") def __str__(self): return f"Banco: {self.nome_banco} Fila: {self.fila_prioridade}" def __repr__(self): return str(self)
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 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 test_exch(count): """Test exchange method.""" heap = MaxHeap() _ = [heap.insert(randint(0, 100)) for i in range(MAX_ITER)] pos_a = randint(0, len(heap.heap) - 1) val_a = heap.heap[pos_a] pos_b = randint(0, len(heap.heap) - 1) val_b = heap.heap[pos_b] heap.exch(val_a, val_b) assert heap.heap[pos_a] == val_b and heap.heap[pos_b] == val_a
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 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 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()
class Median: def __init__(self): self.h_low = MaxHeap() self.h_high = MinHeap() def add_element(self, value): if self.h_low.heap_size == 0 or value < self.h_low.max(): self.h_low.insert(value) if self.h_low.heap_size - self.h_high.heap_size > 1: self.h_high.insert(self.h_low.extract_max()) else: self.h_high.insert(value) if self.h_high.heap_size - self.h_low.heap_size > 1: self.h_low.insert(self.h_high.extract_min()) def get_median(self): if (self.h_low.heap_size + self.h_high.heap_size) % 2 == 0: return self.h_low.max(), self.h_high.min() else: if self.h_low.heap_size > self.h_high.heap_size: return self.h_low.max() else: return self.h_high.min() def get_maxheap_elements(self): return self.h_low.heap def get_minheap_elements(self): return self.h_high.heap
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 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 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()
class CaixaBanco: def __init__(self, nome_banco: str): self.fila_prioridade = MaxHeap() self.nome_banco = nome_banco def adiciona_cliente(self, cliente: Cliente): #print("Cliente: " + f"{cliente.nome}" + "\n" + " Idade: " + f"{cliente.idade}" + "\n" + " Necessidades Especiais: " + f"{cliente.necessidades_especiais}" + "\n") if cliente.idade > 80: prioridade = 3 prioridade_cliente = PrioridadeCliente(cliente, prioridade) self.fila_prioridade.insere(prioridade_cliente) elif ((cliente.idade > 60 and cliente.idade <= 80) or (cliente.necessidades_especiais == True)): prioridade = 2 prioridade_cliente = PrioridadeCliente(cliente, prioridade) self.fila_prioridade.insere(prioridade_cliente) else: prioridade = 1 prioridade_cliente = PrioridadeCliente(cliente, prioridade) self.fila_prioridade.insere(prioridade_cliente) def proximo_cliente(self) -> Cliente: if len(self.fila_prioridade.arr_heap) > 1: prox_cliente = self.fila_prioridade.retira_max() return prox_cliente else: return f"Nao ha mais clientes na fila" def __str__(self): return f"Banco: {self.nome_banco} Fila: {self.fila_prioridade}" def __repr__(self): return str(self)
class PriorityQueue(object): def __init__(self, maxsize=None): self.maxsize = maxsize self._maxheap = MaxHeap(maxsize) def push(self, priority, value): entry = (priority, value) self._maxheap.add(entry) def pop(self, with_priority=False): entry = self._maxheap.extract() if with_priority: return entry else: return entry[1] def is_empty(self): return len(self._maxheap) == 0
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 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 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')])
class MedianMaintenance: def __init__(self): self.hlow_heap = MaxHeap() self.hhigh_heap = MinHeap() def compute_median(self, i): self.insert_heap(i) self.balance_heap() return self.median() def balance_heap(self): if self.hhigh_heap.size - self.hlow_heap.size > 1 : # rebalance heap to keep it balanced high = self.hhigh_heap.extract_min() self.hlow_heap.insert(high) elif self.hlow_heap.size - self.hhigh_heap.size > 1: low = self.hlow_heap.extract_max() self.hhigh_heap.insert(low) def insert_heap(self, i): if self.hlow_heap.is_empty(): low = None else: low = self.hlow_heap.peek_max() if self.hhigh_heap.is_empty(): high = None else: high = self.hhigh_heap.peek_min() if low is None or i < low: self.hlow_heap.insert(i) elif high is not None and i > high: self.hhigh_heap.insert(i) else:# i wedged inbetween insert in first heap by default self.hlow_heap.insert(i) def median(self): if self.hhigh_heap.size - self.hlow_heap.size == 1: return self.hhigh_heap.peek_min() else:# default choice when hlow is bigger/same size as hhigh return self.hlow_heap.peek_max()
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')
class SinglePercentileTracker(object): ''' A class that tracks a single percentile''' def __init__(self, percentile): self.percentile_tracked = percentile self.lheap = MaxHeap() self.rheap = MinHeap() self.size = 0 self.percentile = None def add(self, num): # An addition to a list is O(log n) since look up is O(1) # insertions are O(log n), and worst case pop is O(log n) # and everything is done a constant number of times. In these # cases, n is the size of the larger of the two heaps self.size += 1 n = (self.percentile_tracked / 100.0) * (self.size + 1) # The left heap should always be the floor of n, so we have the # floor(n)th ranked node as the max node in the left heap, and the # min node of the right heap will be the nth+1 ranked node. lsize = int(math.floor(n)) # Push the num on to the proper heap if num > self.percentile: self.rheap.push(num) else: self.lheap.push(num) # if the left heap isn't the right size, push or pop the nodes # to make sure it is. if self.lheap.size() < lsize: self.lheap.push(self.rheap.pop()) elif self.lheap.size() > lsize: self.rheap.push(self.lheap.pop()) # Take the integer part of n and grab the nth and nth+1 # ranked nodes. Then take the nth node as the base # and add the fractional part of n * nth+1 ranked node to get a # weighted value between the two. This is your percentile. ir = int(n) fr = n - ir low_data = self.lheap.get(0) high_data = self.rheap.get(0) self.percentile = fr * (high_data - low_data) + low_data def add_list(self, lst): # Add list is O(k * log n) where k is len(lst) and n is # the size of the larger of the two heaps for l in lst: self.add(l)
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 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 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)
from heap import Heap,MaxHeap import numpy as np if __name__=='__main__': h=Heap() H=MaxHeap() median=[] rootindex=0 with open('Median.txt') as fd: #with open('test10.txt') as fd: no=int(fd.readline()) median.append(no) H.insert(no) no1=int(fd.readline()) h.insert(no1) if no1>no: median.append(no) else: h.heap[0],H.heap[0]=H.heap[0],h.heap[0] median.append(no1) print median for line in fd: no=int(line) if no<=H.heap[0]: H.insert(no) elif no>h.heap[0]: h.insert(no) else: H.insert(no) if len(H.heap)-len(h.heap)>1:
def heap_sort(l): heap = MaxHeap() heap.populate_from_list(l) return [heap.pop() for _ in l]
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)
class TestMaxHeap(unittest.TestCase): def setUp(self): self.heap = MaxHeap() def test_basic_initialization_and_repr(self): self.assertEqual(repr(self.heap), '[]') def test_insert(self): self.heap.insert(4) self.assertEqual(repr(self.heap), '[4]') self.assertEqual(self.heap.size, 1) self.heap.insert(4) self.assertEqual(repr(self.heap), '[4, 4]') self.assertEqual(self.heap.size, 2) self.heap.insert(6) self.assertEqual(repr(self.heap), '[6, 4, 4]') self.assertEqual(self.heap.size, 3) self.heap.insert(1) self.assertEqual(repr(self.heap), '[6, 4, 4, 1]') self.assertEqual(self.heap.size, 4) self.heap.insert(7) self.assertEqual(repr(self.heap), '[7, 6, 4, 1, 4]') self.assertEqual(self.heap.size, 5) def test_get_max(self): self.assertEqual(self.heap.get_max(), None) self.heap.insert(-7) self.assertEqual(self.heap.get_max(), -7) self.heap.insert(7) self.assertEqual(self.heap.get_max(), 7) self.heap.insert(5) self.assertEqual(self.heap.get_max(), 7) self.heap.insert(12) self.assertEqual(self.heap.get_max(), 12) def test_extract_min(self): self.heap.insert(4) self.heap.insert(5) self.heap.insert(7) self.heap.insert(2) self.heap.insert(-1) self.assertEqual(self.heap.extract_max(), 7) self.assertEqual(self.heap.extract_max(), 5) self.assertEqual(self.heap.extract_max(), 4) self.assertEqual(self.heap.extract_max(), 2) self.assertEqual(self.heap.extract_max(), -1) self.assertEqual(self.heap.extract_max(), None) def test_build_heap(self): self.heap.build_heap([4, 4, 6, 1, 7]) self.assertEqual(repr(self.heap), '[7, 4, 6, 1, 4]')
def setUp(self): self.heap = MaxHeap()
def __init__(self): self.hlow_heap = MaxHeap() self.hhigh_heap = MinHeap()
def test_heap(): """Pytest fixture.""" heap = MaxHeap() for _ in range(MAX_ITER): heap.insert(randint(0, 100)) return heap
def __init__(self, percentile): self.percentile_tracked = percentile self.lheap = MaxHeap() self.rheap = MinHeap() self.size = 0 self.percentile = None
def x_sort(S): X = MaxHeap(S) X.heapsort() return X
def heap_sort(numbers): heap = MaxHeap(numbers) heap.sort_increasing()
class HeapMedian: ''' solution using min-, max- heaps ''' def __init__(self): self.upper = MinHeap() self.lower = MaxHeap() def add(self, i): assert self.lower.size() >= self.upper.size() if self.lower.size()==0 or\ i <= self.lower.peek(): self.lower.push(i) else: self.upper.push(i) if self.lower.size() < self.upper.size(): self.lower.push(self.upper.pop()) elif self.lower.size() > self.upper.size()+1: self.upper.push(self.lower.pop()) def get(self): return self.lower.peek()
def __init__(self): self.upper = MinHeap() self.lower = MaxHeap()
from heap import MinHeap, MaxHeap from math import floor import sys #invariant: maintain min heap size = floor(n/2), median is the the max in max heap with open('Median.txt') as f: #with open('median10_test.txt') as f: a = [int(l) for l in f] minHeap = MinHeap([]) maxHeap = MaxHeap([]) medians = [] for i in range(len(a)): if minHeap.size() == 0 and maxHeap.size() == 0: maxHeap.insert(a[i]) else: if a[i] < maxHeap.top(): maxHeap.insert(a[i]) else: minHeap.insert(a[i]) if minHeap.size() > floor((i+1)/2): maxHeap.insert(minHeap.extract()) elif minHeap.size() < floor((i+1)/2): minHeap.insert(maxHeap.extract()) medians.append(maxHeap.top()) print(sum(medians)%10000)
from heap import MaxHeap arr=[36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42] arr=[1, 9, 3, 10, 4, 20, 2] arrlength=len(arr) h=MaxHeap() count=1 if arrlength>0 else 0 cons=[] maxcount=count while len(arr)>0: element=arr.pop() h.insert(element) maxi=h.extractmax() cons.append(maxi) new=0 for i in range(arrlength-1): sec_maxi=h.extractmax() if sec_maxi==maxi-1: count+=1 if count>maxcount: maxcount=count if new==1: cons.append(maxi) new=0 cons.append(sec_maxi) else: count=1 new=1 cons=[] maxi=sec_maxi print maxcount print cons