def solver(): readLine = stdin.readline writeLine = stdout.write cases = int(readLine()) _heap = [] while(cases > 0): enter = readLine() enter = enter.split(' ') if(len(enter) > 1): op, num = [int(x) for x in enter] else: op = int(enter[0].rstrip()) if(op == 1 and num not in _heap): heapq.heappush(_heap, num) heapq._heapify_max(_heap) elif(op == 2): if num in _heap: idx = _heap.index(num) _heap.pop(idx) heapq._heapify_max(_heap) else: writeLine('-1\n') elif(op == 3 and len(_heap) > 0): x = heapq.nlargest(1, _heap) writeLine("{:d}\n".format(x[0])) elif(op == 4 and len(_heap) > 0): x = heapq.nsmallest(1, _heap) stdout.write("{:d}\n".format(x[0])) cases -= 1
def odd_even_array(): #NOTE: Not complete max_val = 0 array1 = [50, 1] array2 = [1, 50] index1 = 0 index2 = 0 #intialize heap_list = [] heapq.heappush(heap_list, (array1[0], 1)) heapq.heappush(heap_list, (array2[0], 2)) #some condition while index1<len(array1) and index2<len(array2): heapq._heapify_max(heap_list) print heap_list temp = heapq.heappop(heap_list) max_val += temp[0] which_array = temp[1] import ipdb; ipdb.set_trace() if which_array == 1: index1 += 1 temp = (array1[index1], 1) heapq.heappush(heap_list, (array1[index1], 1)) else: index2 += 1 heapq.heappush(heap_list, (array2[index2], 2)) heapq.heappush(heap_list, temp) #if more return max_val
def get_median(): minheap, maxheap = [], [] heapq.heapify(minheap) heapq._heapify_max(maxheap) median = 0 while True: val = random.random() if minheap==None and maxheap==None: heapq.heappush(minheap, val) median = val elif minheap and maxheap==None: heapq._heappushpop_max(maxheap, val) elif minheap==None and maxheap: heapq.heappush(minheap, maxheap[0]) heapq.heappop(maxheap) else: if val<minheap[0]: heapq.heappush(minheap, val) else: heapq._heappushpop_max(maxheap, val) if len(minheap)>len(maxheap)+1: heapq.heappush(minheap, heapq.heappop(maxheap)) elif len(minheap)+1<len(maxheap): heapq._heappushpop_max(maxheap, heapq.heappop(minheap)) if minheap or maxheap: if len(minheap)==len(maxheap): median = (minheap[0]+maxheap[0])/2 elif len(minheap)>len(maxheap): median = minheap[0] else: median = maxheap[0] print median
def find_min_k_elements(arr, k): if not arr: raise AttributeError("Can't have an empty array") if len(arr) <= k: arr.sort() return arr # k is less than N heap = [] for i in range(k): heap.append(arr[i]) # create a max heap heapq._heapify_max(heap) for i in range(k, len(arr)): element = arr[i] if element < heap[0]: heapq.heappop(heap) heap.append(element) heapq._heapify_max(heap) return heap
def answer(n): stk = [] que = [] heap = [] is_stk = is_que = is_heap = True for i in xrange(n): c, e = map(int, raw_input().split()) if c == 1: stk.append(e) que.append(e) heappush(heap, e) else: if is_stk and len(stk) > 0 and e != stk.pop(): is_stk = False if is_que and len(que) > 0 and e != que.pop(0): is_que = False if is_heap and len(heap) > 0: _heapify_max(heap) if e != heappop(heap): is_heap = False if not is_stk and not is_que and not is_heap: return 'impossible' if (is_stk and is_que) or (is_stk and is_heap) or (is_que and is_heap): return 'not sure' if is_stk: return 'stack' if is_que: return 'queue' if is_heap: return 'priority queue'
def solveOne(self, A, B): x = product(A, B) h = [] for pair in x: h.append(sum(pair)) heapq._heapify_max(h) print heapq._nlargest(len(A), h)
def append(self, new_song): """Append a song to the queue""" if isinstance(new_song, Song): self.queue.append(new_song) else: self.queue.append(Song(new_song)) heapq._heapify_max(self.queue)
def __init__(self, *song): # parsing the parameters for s in song: self.queue.append(s) heapq._heapify_max(self.queue) logging.info("playlist created with " + str(self.get_list_of_all()) + " as start value")
def get20MostInterestingFrequentWords(): filter = open("most-common-EnglishWords-100.txt","r") filter_words = filter.readlines() for i in range(len(filter_words)): filter_words[i] = filter_words[i].strip("\n") frequency_dict = dict() for word in WORDS: if word.lower() not in filter_words: if word.lower() in frequency_dict: frequency_dict[word.lower()] += 1 else: frequency_dict[word.lower()] = 1 frequency_list = [] for k in frequency_dict: frequency_list.append([frequency_dict[k], k]) heapq._heapify_max(frequency_list) return_list = [] for i in range(20): return_list.append(heapq._heappop_max(frequency_list)) return return_list
def maximumAmount(scalpers, k): tot = 0 for i in range(k): heapq._heapify_max(scalpers) tot += scalpers[0] scalpers[0] -= 1 return tot
def downvote_song(self, song): """Downvote song in the queue""" for s in self.queue: if s == song or s.get_name() == song: s.downvote() heapq._heapify_max(self.queue) return 0 return 1
def med(n, lst, k): assert n == len(lst) assert n > k l = lst[0:k] heapq._heapify_max(l) for i in range(k, n): if lst[i] < l[0]: heapq._heappushpop_max(l, lst[i]) return l[0]
def delete(self, song): """Delete a song from the queue""" for s in self.queue: # checking if ether $song or a $song.name is in the queue if s == song or s.get_name() == song : self.queue.remove(s) # building a new heap after deleting heapq._heapify_max(self.queue) logging.debug(song + "deleted => " + str(self.get_list_of_all())) return 0 return 1
def solve(self, A, B): h = [] cnt = 0 #A = sorted(A, reverse=True) #B = sorted(B, reverse=True) d = dict() for x in product(A, B): sum_pair = sum(x) h.append(sum_pair) heapq._heapify_max(h) return heapq._nlargest(len(A), h)
def findKthLargest(nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums_heap = nums heapq._heapify_max(nums_heap) for i in range(k-1): nums_heap.pop(0) heapq._heapify_max(nums_heap) return nums_heap.pop(0)
def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ heapq._heapify_max(nums) for i in range(k): if i + 1 == k: return heapq.heappop(nums) else: heapq.heappop(nums) heapq._heapify_max(nums)
def heapSort(arr): resultArr = [0] * len(arr) n = len(arr) - 1 while(n != 0): _heapify_max(arr) resultArr[n] = arr[0] arr[0], arr[n] = arr[n], arr[0] arr.pop() n -= 1 resultArr[n] = arr[0] print(resultArr)
def prog_11(fname): f = open(fname) n = map(int, f.readline().strip()) l = map(int, f.readline().strip().split()) f.close() print n print l heapq._heapify_max(l) f = open('result.dat','w') for v in l: f.write(str(v)+'\t') f.close()
def _max_heapify_at_a_range(numbers, left, right): """ Build max-heap in a range of the array. Parameters ---------- numbers: list List of numbers to be sorted. left: int Initial index. right: int Final index. """ part = slice(left, right + 1) partial = numbers[part] heapq._heapify_max(partial) numbers[part] = partial
def get20MostFrequentWords(): frequency_dict = dict() for word in WORDS: if word.lower() in frequency_dict: frequency_dict[word.lower()] += 1 else: frequency_dict[word.lower()] = 1 frequency_list = [] for k in frequency_dict: frequency_list.append([frequency_dict[k], k]) heapq._heapify_max(frequency_list) return_list = [] for i in range(20): return_list.append(heapq._heappop_max(frequency_list)) return return_list
def get_median(max_h,min_h): heapq._heapify_max(max_h) heapq.heapify(min_h) if len(max_h) == len(min_h): temp = (max_h[0] + min_h[0])/2.0 elif len(max_h) - len(min_h) == 1: temp = max_h[0] elif len(min_h) - len(max_h) == 1: temp = min_h[0] else: if len(max_h) - len(min_h) > 1: heapq.heappush(min_h,heapq.heappop(max_h)) elif len(min_h) - len(max_h) > 1: heapq.heappush(max_h,heapq.heappop(min_h)) return get_median(max_h,min_h) return temp
def solve(arr): # to remove duplicates. cast back to list to pass to heapq distinct_arr = list(set(arr)) # undocumented method of heapq. could also invert values of arr # to negative and use the usual methods to achieve a max heap. heapq._heapify_max(distinct_arr) # nodes of a heap (indexed starting at 0) have the following properties: # left child = (2 * i) + 1 # right child = (2 * i) + 2 # the root node is 0 # the root node is the max element. # # all this is to say, to return the 2nd most maximum element, we need # only find the max of the i=1 and i=2 values (the left and right children # of the root node). # So, let's do that. return max(distinct_arr[1:3])
def test(): ''' ''' max_heap = MaxHeap() for i in range(10): max_heap.insert(i) # freeze the test data max_heaped_arr = tuple(max_heap.arr[:1]) # use the system libraries test_heap = list(max_heaped_arr) heapq._heapify_max(test_heap) assert max_heaped_arr == tuple(test_heap) # test the collection initializer l = range(10) heapq._heapify_max(l) assert tuple([None] + l) == tuple(MaxHeap(range(10)).arr)
def _heapsort_algo(numbers): """ Sorts "in situ" a list of numbers in ascendant order using the Insertion Sort method for the entire list. >>> array = [5, 1, 8, 9, 2] >>> _heapsort_algo(array) >>> array [1, 2, 5, 8, 9] Parameters ---------- numbers: list List of numbers to be sorted. """ left, right = 0, len(numbers) - 1 heapq._heapify_max(numbers) while right >= 1: number = numbers[0] swap(numbers, 0, right) right -= 1 _max_heapify_at_a_range(numbers, left, right)
def medians(li,minH = [],maxH = [],mD = []): if len(li) <= 1: return li while(li != []): var = li.pop(0) if len(minH) + len(maxH) == 0: heapq.heappush(minH,var) heapq.heapify(minH) if mD != []: if var >= mD[len(mD)-1]: heapq.heappush(minH,var) heapq.heapify(minH) elif var <= mD[len(mD)-1]: heapq.heappush(maxH,var) heapq._heapify_max(maxH) if len(minH) - len(maxH) == 1 : mD.append(minH[0]) if len(maxH) - len(minH) == 1: mD.append(maxH[0]) if len(minH) == len(maxH) and len(minH) + len(maxH) != 0: mDvar = (minH[0] + maxH[0])/2.0 varS = str(mDvar) varLast = int(varS[len(varS)-1]) if varLast > 0: mD.append(mDvar) else: mD.append(int(mDvar)) if abs(len(minH) - len(maxH)) > 1: if len(minH) > len(maxH): while(len(minH) - len(maxH) != 1): heapq.heappush(maxH, heapq.heappop(minH)) heapq._heapify_max(maxH) elif len(maxH) > len(minH): while(len(maxH) - len(minH) != 1): heapq.heappush(minH,heapq.heappop(maxH)) heapq.heapify(minH) return mD
def max_sliding_window_heap(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if nums is None or len(nums) == 0 or k == 0: return [] if len(nums) <= k: return [max(nums)] if k == 1: return nums ret = [] heap = nums[:k] heapq._heapify_max(heap) # O(N) ret.append(heap[0]) for i in range(k, len(nums)): remove_index = heap.index(nums[i - k]) heap[remove_index] = heap[-1] # remove heap[-1] = nums[i] # move window right by one heapq.heapify(heap) # re-heapify, or use _siftup_max ret.append(heap[0]) return ret
def getSkyline(self, buildings): """ :type buildings: List[List[int]] :rtype: List[List[int]] """ if len(buildings) == 0: return [] building_list = [] for x in range(len(buildings)): building_list.append(f(buildings[x][0], buildings[x][2], 1)) building_list.append(f(buildings[x][1], buildings[x][2], 0)) building_list = sorted(building_list) for buil in building_list: print buil.x, buil.h, buil.s heap = [0] result = [] curr_max = heap[0] for building in building_list: heapq._heapify_max(heap) if building.s: heap.append(building.h) heapq._heapify_max(heap) new_max = heap[0] if curr_max != new_max: result.append([building.x, building.h]) curr_max = new_max else: heap.remove(building.h) heapq._heapify_max(heap) new_max = heap[0] if new_max != curr_max: result.append([building.x, new_max]) curr_max = new_max return result
# coding=utf-8 __author__ = "PyBeaner" import heapq from random import sample alist = sample(range(10), 10) print(alist) heapq.heapify(alist) print(alist) # 已经是一个最小堆 alist = list(range(10)) print(alist) heapq.heapify(alist) print(alist) alist = list(range(10, 0, -1)) # maxheap heapq._heapify_max(alist) print(alist)
def solution(k): array = [1, 2, 3, 5] if k < 6: return k queue_1 = deque() queue_2 = deque([[2, 2], [3, 3], [5, 5]]) while True: while queue_2: item = queue_2.popleft() if item[1] == 2: for i in [2, 3, 5]: queue_1.append([item[0] * i, i]) array.append(item[0] * i) elif item[1] == 3: for i in [3, 5]: queue_1.append([item[0] * i, i]) array.append(item[0] * i) else: queue_1.append([item[0] * 5, 5]) array.append(item[0] * 5) if len(array) - 1 >= k: queue_life = queue_1 break while queue_1: item = queue_1.popleft() if item[1] == 2: for i in [2, 3, 5]: queue_2.append([item[0] * i, i]) array.append(item[0] * i) elif item[1] == 3: for i in [3, 5]: queue_2.append([item[0] * i, i]) array.append(item[0] * i) else: queue_2.append([item[0] * 5, 5]) array.append(item[0] * 5) if len(array) - 1 >= k: queue_life = queue_2 break while len(array) != k: heapq._heapify_max(array) array.pop(0) heapq._heapify_max(array) while queue_life: item = queue_life.popleft() if item[1] == 2: for i in [2, 3, 5]: if item[0] * i < array[0]: array[0] = item[0] * i queue_life.append([item[0] * i, i]) heapq._heapify_max(array) if item[1] == 3: for i in [3, 5]: if item[0] * i < array[0]: array[0] = item[0] * i queue_life.append([item[0] * i, i]) heapq._heapify_max(array) if item[1] == 5: if item[0] * 5 < array[0]: array[0] = item[0] * 5 queue_life.append([item[0] * 5, 5]) heapq._heapify_max(array) return array[0]
def searchEngine_2(query): query = CleanData(query) inverted_index = json.loads(open("inverted_index.json").read()) inverted2_index = json.loads(open("inverted2_index.json").read()) vocabulary = json.loads(open("vocabulary.json").read()) Idf_dict = json.loads(open("Idf_dict.json").read()) index = [] # I calculate the tf of the word in the query since the query is a set is always given by 1 fraction the length of the set query_words_tf = 1 / len(query) query = set(query) # this part is identical to the search engine 1 for par in query: if par in vocabulary.keys(): index.append(vocabulary[par]) docs = [] if len(index) != len(query): return print("There are no results that match your query.") else: for indices in index: docs.append(set(inverted_index[str(indices)])) docs = set.intersection(*docs) if len(docs) == 0: return print('there are no articles that contain all the words.') else: lst2 = [] # for each document for d in docs: lst = [] lst1 = [] # for word in the document i calculate the cosine similarity between words in the document and words in the query for i in index: c = inverted2_index[str(i)] for val in c: if val[0] == d: lst.append(val[1]) b = Idf_dict[str(i)] for val1 in b: if val1[0] == d: lst1.append(val1[1] * query_words_tf) cosine = [ d, round(dot(lst, lst1) / (norm(lst) * norm(lst1)), 3) ] lst2.append(cosine) # I create a maxheap where I keep documents with relative similarity q = [(x[1], x[0]) for x in lst2] heapq._heapify_max(q) k = 5 lst4 = [] for i in range(k): try: c = heapq._heappop_max(q) lst4.append(c) except IndexError: break result = pd.DataFrame() # I create the db to be returned with the first 5 elements with greater similarity d_url = json.loads(open("d_url.json").read()) for tupla in lst4: z = d_url[tupla[1]] df2 = pd.DataFrame({'similarity': tupla[0]}, index=[0]) df1 = pd.DataFrame({'link': z}, index=[0]) df = pd.read_csv(tupla[1] + ".tsv", delimiter="\t") result1 = df[['title', 'intro', 'plot']] result2 = pd.concat([result1, df1, df2], axis=1) result = result.append(result2) result.reset_index(drop=True, inplace=True) print(result)
# 1. include index 0 # 2. pop method returns the smallest item def heapsort(iterable): h = [] for values in iterable: heappush(h, values) return [heappop(h) for i in range(len(h))] print(heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])) alist = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] _heapify_max(alist) print(alist) # heapify(alist) # heapsort(alist) heapreplace(alist, 10) merged = merge([1, 2, 3, 4], [2, 3, 6, 7]) print([_ for _ in merged]) print(nlargest(3, alist)) print(nsmallest(3, alist))
import heapq listfortree = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] minheap = heapq.heapify(listfortree) maxheap = heapq._heapify_max(listfortree) print heapq.heappop(listfortree) print heapq._heappop_max(listfortree) print minheap, maxheap
import heapq # 虽然显示红色,但是可以运行 from heapq import _heapify_max, _heappop_max, _heapreplace_max list = [1, 2, 3] _heapify_max(list) print(list) print(_heappop_max(list)) print(list) print(_heapreplace_max(list, 3)) print(list)
import heapq as hp operation = [] N = int(input()) for i in range(N) : x = str(input()) operation.append(x) heap = [] for op in operation : if op[0] == "I" : hp.heappush(heap, int(op[2:])) elif op == "D 1" : if answer == [] : continue hp._heapify_max(heap) hp.heappop(heap) elif op == "D -1" : if answer == [] : continue hp.heapify(heap) hp.heappop(heap) if heap == [] : heap = [0, 0] print(heap) print("Done") elif len(heap) == 1 : min = heap[0] ; max = heap[0] heap = [max, min] print(heap) else : hp.heapify(heap) min = hp.heappop(heap) hp._heapify_max(heap) max = hp.heappop(heap)
def from_list(self, arr): self.heap = arr.copy() heapq._heapify_max(self.heap)
import sys from queue import PriorityQueue import heapq my_arr = [[4, 'Read'], [2, 'Play'], [5, 'Write'], [1, 'Code'], [3, 'Study']] heapq.heapify(my_arr) heapq._heapify_max(my_arr) # q = PriorityQueue() # q.put([4, 'Read']) # q.put([2, 'Play']) # q.put([5, 'Write']) # q.put([1, 'Code']) # q.put([3, 'Study']) # while not q.empty(): # next_item = q.get() # # print(next_item) class Solution: def leastInterval(self, tasks, n): freq_of_tasks = {k: tasks.count(k) for k in tasks} my_tasks = [] for k, v in freq_of_tasks.items(): my_tasks.append([v, k]) heapq.heapify(my_tasks)
def add_live_node(up, lev, par, ch, heap): heap.append(HeapNode(BBNode(par, ch), up, lev)) heapq._heapify_max(heap)
a, b = b, a % b return a def lcm(a, b): """Return lowest common multiple.""" return a * b // gcd(a, b) """def lcm(x, y): if x > y: greater = x else: greater = y while True: if (greater % x == 0) and (greater % y == 0): l = greater break greater += 1 return l""" import heapq listForTree = [1,2,3,4,5,6,7,8,9,10,11,25, 12,13,14,15] heapq._heapify_max(listForTree) for i in range(4): print heapq.heappop(listForTree) heapq._heapify_max(listForTree)
def kLargestElement(li,k): heapq._heapify_max(li) return li[k-1]
current_samples = [] for (crop_left, crop_top), current_score in zip(classification[3], classification[4].ravel()): current_samples.append( Sample(image_name, current_score, crop_top, crop_left, crop_top + win_height, crop_left + win_width) ) else: current_samples = [Sample(image_name)] if classification[0] == category.name: scores[index] = 1 category.correct_samples += current_samples else: for sample in current_samples: if len(category.incorrect_samples) < (num_images): category.incorrect_samples.append(sample) heapq._heapify_max(category.incorrect_samples) else: heapq._heappushpop_max(category.incorrect_samples, sample) cv2.imwrite(output_folder + classification[0] + "_" + image_name, classification[1]) print "{} [{} out of {}]".format(classification[0], index + 1, num_images) print "Accuracy = %.2f%%" % (100.0 * np.sum(scores) / num_images) ######################################################################################## # Re train on incorrect results from negative incorrect samples female_category = next(category for category in categories if category.name == "female") images_folder = "data/segmented_image/colour/" # TODO - REMOVE A SAMPLE FROM THE SAME IMAGE YOU ARE REPLACING WITH - IF POSSIBLE? output_folder = "data/cropped_wing/female/"
import heapq heapList = [6, 2, 3, 4, 5, 10, 20] heapq.heapify(heapList) print heapList heapq._heapify_max(heapList) print heapList heapq.heapreplace(heaplist, 15) print heapList
def addToMaxHeap(self, element): print("Adding element to max heap", element) self.maxHeap.append(element) heapq._heapify_max(self.maxHeap)
def main(debts, discretionary, method, actionMonths): g = nextMonthGen() if method == 'avalanche': _heapify_max(debts) # max-heap: (i.e. descending order) else: heapify(debts) # min-heap results = [] executedDebts = [] shouldRemove = [] totalDiscretionary = discretionary count = 1 month, year = next(g) while debts: termDiscretionary = totalDiscretionary for debt in debts: #logic here to differentiate loan types if type(debt) == StandardAmortized: interest = round(debt.balance * (debt.rate / 12), 2) principal = round(debt.minPayment - interest, 2) debt.balance -= principal elif type(debt) == CreditCard: # daily rate * balance * days this cycle interest = round( debt.balance * (debt.rate / 365) * monthDayMap.get(month), 2) principal = round( (debt.minPaymentPercentage * debt.balance) - interest, 2) debt.balance -= principal elif type(debt) == Heloc: interest = round((debt.balance * (debt.rate / 365)) * monthDayMap.get(month), 2) principal = round(debt.minPayment - interest, 2) debt.balance -= principal if termDiscretionary > 0: # subtract extra discretionary from highest weighted debt(s) debt.balance -= round(termDiscretionary, 2) principal += termDiscretionary if count <= actionMonths: debt.actions.append( [interest, principal, datetime(year, month, 1).date()]) debt.totalInterest += interest debt.totalInterest = round(debt.totalInterest, 2) # reset balance, add metadata, and dequeue if debt.balance <= 0.0: # reset balance (add difference in balance back to discretionary) *** possible error here in else case *** should be zero? termDiscretionary = termDiscretionary + ( debt.balance * -1) if debt.balance < 0.0 else termDiscretionary debt.balance = 0.0 debt.periodsToPayoff = count debt.payoffDate = (month, year) debt.calculatePossibleInterestSavings() print( f"debt: {debt.name} periods: {debt.periodsToPayoff} max periods: {debt.maxInterest} payoff Date: {debt.payoffDate} total paid interest {debt.totalInterest} max interest possible: {debt.maxInterest} interest savings: {debt.possibleInterestSavings}" ) print("actions: ") print(debt.actions) results.append([ debt.name, debt.periodsToPayoff, debt.payoffDate, debt.maxPeriods, debt.totalInterest, debt.maxInterest ]) executedDebts.append(debt) shouldRemove.append(debt) month, year = next(g) count += 1 for debt in shouldRemove: debts.remove(debt) shouldRemove = [] return results, executedDebts
if len(heap) < pos + 1: return num_empty = 2**depth - 1 empty_list = [" " for i in range(num_empty)] line = empty_list + [heap[pos]] + empty_list if len(heap_graph) < level + 1: heap_graph.append(line) else: heap_graph[level] = heap_graph[level] + [' '] + line childleft = 2 * pos + 1 childright = childleft + 1 gen_heap_graph(heap_graph, heap, childleft, depth - 1, level + 1) gen_heap_graph(heap_graph, heap, childright, depth - 1, level + 1) def print_heap(heap): depth = cal_depth(heap) heap_graph = [] gen_heap_graph(heap_graph, heap, 0, depth - 1, 0) for line in heap_graph: linestr = ''.join([str(item) for item in line]) print linestr if __name__ == "__main__": h1 = [12, 2, 33, 4, 5, 6, 7, 81, 9, 10] heapq._heapify_max(h1) print heappop_max(h1) heappush_max(h1, 50) print_heap(h1)
# For example: # Array is [5, 3, 9, 1], n is 4 # k = 0 => 9 # k = 1 => 5 # k = 3 => 1 #!/usr/bin/env python import heapq arr = [5, 3, 9, 1] k = 2 # maintain max heap (this is a little ugly since heapq does not do max heap # using heappop and heappush, it does a min heap) heap = [] for num in arr: heapq._heapify_max(heap) if len(heap) < k: heapq.heappush(heap, num) else: top = heap[0] # if next num is < top then push if top > num: heap[0] = num heapq._heapify_max(heap) print(heap[0])
# 小顶堆 print('小顶堆+数值') # heapq.heapify(d) #或者 heap = [] for x in d: heapq.heappush(heap, x) for i in range(len(d)): v = heapq.heappop(heap) print(v, end=' ') print('') #大顶堆 print('大顶堆+数值') d = [2, 3, 1, 7, 6, 8] heapq._heapify_max(d) for i in range(len(d)): v = heapq._heappop_max(d) print(v, end=' ') print('') print('小顶堆+自定义类型') class MinHeapObj(object): #e.g. 先按总排序,再按数学分数排序 def __init__(self, score_sum, score_math): self.score_sum = score_sum self.score_math = score_math def __lt__(self, other): return self.score_sum < other.score_sum \
start_node, end_node = [ int(p) for p in input().split('Path: ')[-1].split(' – ') ] edge_count = int(input().split('Edges: ')[-1]) graph = {node: [] for node in range(node_count)} distance = {node: -1 for node in range(node_count)} distance[start_node] = 0 prev = {node: node for node in range(node_count)} for _ in range(edge_count): node_a, node_b, weight = [int(p) for p in input().split()] edge = Edge(node_a, node_b, weight) graph[node_a].append(edge) max_heap = graph[start_node] heapq._heapify_max(max_heap) while max_heap: safest_edge = heapq._heappop_max(max_heap) new_dist = distance[safest_edge.node_a] + safest_edge.weight if distance[safest_edge.node_b] < new_dist: # Found a safer path distance[safest_edge.node_b] = new_dist # add the new node's edges with updated overall safety max_heap.extend( Edge(edge.node_a, edge.node_b, edge.weight + new_dist) for edge in graph[safest_edge.node_b]) prev[safest_edge.node_b] = safest_edge.node_a heapq._heapify_max(max_heap) print(build_path(end_node, prev))
#rosalind_hea import heapq f = open('rosalind_hea.txt') n = int(f.readline().rstrip()) a = [int(i) for i in f.readline().rstrip().split()] heapq._heapify_max(a) result = [str(i) for i in a] open('rosalind_hea_sub.txt', 'wt').write(' '.join(result))
data = [-x for x in data] print(sorted(data)) heapq.heapify(data) print(data) print(heapq.heappop(data)) print(data) copy = data[:] print(copy.pop(0)) print(data) print(copy) heapq.heappush(data, 2) heapq.heappush(data, 19) heapq.heappush(data, 21) heapq._heapify_max(data) print(heapq._heappop_max(data)) print(data) l1 = [10, 20, 30, 40, 50] l2 = [15, 25, 35, 45, 55] l3 = heapq.merge(l1, l2) print(list(l3))
Usefull: http://stackoverflow.com/questions/33024215/built-in-max-heap-api-in-python import heapq def _heappush_max(heap, item): heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) def _heappop_max(heap): lastelt = heap.pop() if heap: returnitem = heap[0] heap[0] = lastelt heapq._siftup_max(heap, 0) return returnitem return lastelt h=[] n = int(input()) i = 0 heapq._heapify_max(h) while i<n: s = str(input()) if s.split()[0] =='ExtractMax': print(_heappop_max(h)) elif s.split()[0] =='Insert': _heappush_max(h,int(s.split()[1])) i = i + 1
biggerhalf += 1 smallerhalf = currentmax - biggerhalf heapq.heappush(maxheap2, smallerhalf) heapq.heappush(maxheap2, biggerhalf) heapq._heapify_max(maxheap2) return min(currentmax, minFlips(maxheap) + 1, minFlips(maxheap2) + 1) for line in myfile: if fileinput.isfirstline(): maxcases = int(line.strip()) continue initialdiners = int(line.strip()) line = myfile.readline().strip() dinerPlates = [int(s) for s in line.split()] heapq._heapify_max(dinerPlates) currentcase += 1 sys.stdout.write("Case #" + str(currentcase) + ": ") sys.stdout.flush() print minFlips(dinerPlates) if maxcases == currentcase: break
import heapq listForTree = [2,1,3,4,5,6,7,8,9,10,11,12,13,14,16,17] heapq.heapify(listForTree) # for a min heap print(heapq.heappop(listForTree), " Min") # pop from minheap # 이거 하면 1이 출력 # Time comp - O(logn) listForTree = [2,1,3,4,5,6,7,8,9,10,11,12,13,14,16,17] heapq._heapify_max(listForTree) # for a maxheap!! print(heapq._heappop_max(listForTree), " Max") # pop from maxheap # 이거하면 17 출력 # Time comp - O(logn) ################################################################################ # 파이썬 파이너리 써치.. import bisect li = [1, 3, 4, 4, 4, 6, 7] i = 4 print(bisect.bisect_left(li, i)) print(bisect.bisect_right(li, i)) 로 하면.. 2, 5가 나옴 구현한다면.... # Check base case O(logN) def binary_search(arr, low, high, x): if high >= low: mid = (high + low) // 2 # If element is present at the middle itself if arr[mid] == x: return mid
d["a"] = 1 d["b"] ########binary search############### import bisect a = [1,3,5] bisect.bisect_left(a, 2) #1. log(n) a.insert(1,2) #a = [1,2,3,5] bisect.insort_left(a, 2) # for insert, ####priority queue with heapq import heapq lo = [] hi = [] heapq.heapify(lo) #n*log(n), in place change, lo[0] is the smallest one, lo.pop(0) heapq._heapify_max(hi) heapq._heapreplace_max(a, 7) heapq._heappop_max(a) def _heappush_max(heap, item): heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) heapq.heappush(lo, value) #log(n) for push and pop value = heapq.heappop(lo) heapsort(iterable): h = [] for value in iterable: heappush(h, value) return [heappop(h) for i in range(len(h))] ########deal with file ####################
# It's a list of tasks which represents the order of execution Harmonogram = [] # While lists are not empty while len(NSet) != 0 or len(GSet) != 0: # While smallest time of accessibility is smaller than actual moment in time (and Nset is not empty) while len(NSet) != 0 and min(NSet).r <= t: # Task with smallest r is removed from NSet and added to variable e # heapq library makes a list behave like a heap, where Nset is a min-heap, Gset is a max-heap e = heapq.heappop(NSet) # e is appended to list, from now on NsetTask became GsetTask GSet.append(GsetTask(e)) # Apparently you always have to heapify (make heap out of list) when you have populated list # Otherwise algorithm doesn't work heapq._heapify_max(GSet) # In a situation where Gset is empty, t = smallest r in Nset if len(GSet) == 0: t = min(NSet).r else: # e = GsetTask with highest q e = heapq._heappop_max(GSet) # Saving order of execution Harmonogram.append(e) # Actual moment in time = Previous moment in time + time of execution of this task t = t + e.p # Max time of delivery = Hiqhest of old Cmax vs actual time + time of delivery Cmax = max(Cmax, t + e.q) print("Cmax: ", Cmax)
# import heapq # a = [1,2,3,4,5,6,7,8,9,10] # b = [1,2,3,4,5,6,7,8,9,10] # heapq.heapify(a) # heapq.heapify_max(b) # print(heapq.heappop(minheap)) # print(heapq.heappop(maxheap)) ''' import heapq class MaxHeap(object): def __init__(self): self.h = [] def heappush(self, x): heapq.heappush(self.h, x) def heappop(self): return heapq.heappop(self.h) def __getitem__(self, i): return self.h[i] def __len__(self): return len(self.h) class MaxHeap(MinHeap): def heappush(self,x): heapq.heappush(self.h, ) ''' import heapq arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] heapq.heapify(arr) # for a min heap print(arr) heapq._heapify_max(arr) # for a maxheap!! print(arr)
#Assigning first random chromosome as best answer, it can be updated futher best_ans = chromo #Optimize population for i in population: optimize(population[i], M) #Evaluating population value = [ ] #priority queue to store population in increasing order of fitness value for i in population: val = fitness(population, i, M) value.append([val, i]) if value[0][0] > best_ans_val: best_ans = population[i] heapq._heapify_max(value) iterations = 0 while (not stop_criteria(population, M) and iterations < 1000): print("Iteration " + str(iterations + 1) + " going on") #Selecting parents new_population = {} for i in range(top_k): new_population[value[i][1]] = population[value[i][1]] population = new_population.copy() new_population.clear() #Crossover to produce children new_population = population.copy() for i in population:
def iterative_deepening_alpha_beta(self): ''' I dont think this is working correctly -- i believe when things are getting cached because it doesnt take in consideration the depth of the call of that minimax evaluation we need to take into consideration the depth for it to call correctly need to change this ''' MAX_ITER = 100 # default policy available_actions = self.board.update_actions(self.board, self.player) # self.actions_leftover = self.board.update_actions(self.board, self.player) if len(available_actions) == 0: return None else: # lets just set the default to the first move move = available_actions[0] # time allocated per move in ms self.time_alloc = 0 if self.board.phase == constant.PLACEMENT_PHASE: self.time_alloc = 500 else: self.time_alloc = 1000 # get time start_time = MinimaxABOptimised.curr_millisecond_time() best_depth = 1 # iterative deepening begins here for depth in range(1, MAX_ITER): print(depth) # invalidate / clear the cache when increasing the search depth cutoff self.min_value.cache_clear() try: #self.max_value.cache_clear() # peform the search self.time_rem = self.time_alloc self.time_start = self.curr_millisecond_time() move = self.alpha_beta_minimax(depth, available_actions) print(move) self.time_end = self.curr_millisecond_time() self.time_rem = self.time_alloc - (self.time_end - self.time_start) # after one iteration of ab search we can order the moves based on the actions that # the previous depth evaluated the actions at available_actions = [] while len(self.actions_evaluated) > 0: (val, action) = heapq._heappop_max(self.actions_evaluated) available_actions.append(action) # transform the heap into a max heap heapq._heapify_max(self.actions_evaluated) # update the available_actions list available_actions = available_actions + self.actions_leftover best_depth += 1 except TimeOut: print("TIMEOUT") break if MinimaxABOptimised.curr_millisecond_time( ) - start_time > self.time_alloc: break self.eval_depth = best_depth return move
def get_max(self): return heapq._heapify_max(self.storage)
ex. rightHeap about to grow to be >2 than leftHeap heappush the median to the left heap median is now the heappop of the right heap add the item to the right For left just repeat """ #Set up #Todo, move this above the comments curMedian = 0 leftHeap = map(ReverseCompare, []) rightHeap = [] heapq.heapify(rightHeap) heapq._heapify_max(leftHeap) def runningMed(n): #importing the global variables global curMedian global leftHeap global rightHeap #The first time if (curMedian == 0): curMedian = n return curMedian #the second +... time print "***************Start Right Here******************" print "***n is: " + str(n) print "***curMedian is: " + str(curMedian)
child[i] = mch[i] return child # %% population(wts) for i in ppln: s = sum(i[1]) if i[0] in wtdic: continue h.append(i) wtdic[i[0]] = s if len(wtdic) == size: break pq._heapify_max(h) # %% for k in range(10000): ngen = crossover(h) child = mutate(ngen) addc(child) h.sort() tt = [] for x in h: tt.append(x[0]) print(tt[:10])