コード例 #1
0
def buyTickets(lst, k):
    max_heap = []
    q = [int(i) for i in range(len(lst))]

    for i in lst:
        heapq.heappush(max_heap, i)

    heapq._heapify_max(max_heap)
    time = 0
    print(q, max_heap)
    while len(max_heap) != 0:
        peekIndex = q[0]
        peekElement = lst[peekIndex]
        print(peekElement, max_heap[0])
        if peekElement == max_heap[0]:
            if peekIndex == k:
                return time + 1
            else:
                time = time + 1
                q.pop(0)
                heapq._heappop_max(max_heap)

        else:
            a = q.pop(0)
            q.append(a)
コード例 #2
0
 def thirdMax(self, nums: List[int]) -> int:
     nums = list(set(nums))
     heapq._heapify_max(nums)
     if len(nums) > 2:
         heapq._heappop_max(nums)
         heapq._heappop_max(nums)
     return heapq._heappop_max(nums)
コード例 #3
0
    def leastInterval(self, tasks: List[str], n: int) -> int:
        mapaz = [0 for _ in range(26)]

        for c in tasks:
            mapaz[ord(c) - ord('A')] += 1

        queue = list(filter(lambda x: x > 0, mapaz))
        heapq._heapify_max(queue)

        time = 0
        while queue:
            i = 0
            tmp = []
            while i <= n:
                if queue:
                    if queue[0] > 1:
                        tmp.append(heapq._heappop_max(queue) - 1)
                    else:
                        heapq._heappop_max(queue)
                time += 1
                if (not queue and len(tmp) == 0):
                    break
                i += 1
            for i in tmp:
                heapq.heappush(queue, i)
        return time
コード例 #4
0
    def getTask(self, my_tasks, cannot_use, temp, n):
        task, temp2, val = None, None, None
        if len(cannot_use) == 0:
            task = heapq._heappop_max(my_tasks)
            task[0] = task[0] - 1
            if task[0] != 0:
                temp[task[1]] = task[0]
                cannot_use[task[1]] = n
            return task[1]
        else:
            for job in cannot_use:
                if cannot_use[job] > 0:
                    cannot_use[job] -= 1
                if cannot_use[job] == 0:
                    temp2 = job
            if temp2 is not None:
                cannot_use.pop(temp2)
                val = temp.pop(temp2)
            if len(my_tasks) > 0:
                if val is not None:
                    my_tasks.append([val, temp2])
                    val = None
                print(my_tasks)
                task = heapq._heappop_max(my_tasks)
                task[0] = task[0] - 1
                if task[0] != 0:
                    temp[task[1]] = task[0]
                    cannot_use[task[1]] = n
            if val is not None:
                my_tasks.append([val, temp2])

        return task[1] if task else None
コード例 #5
0
def solution(operations):
    # ans = []
    # for oper in operations:
    #     c, n = oper.split()
    #     # print(f"c: {c}, n: {n}, ans: {ans}")
    #     if c == "I":
    #         ans.append(int(n))
    #         ans.sort()
    #     elif ans:
    #         ans.pop() if n == "1" else ans.pop(0)
    # return [ans[-1], ans[0]] if ans else [0, 0]

    # code refactoring - using heapq
    res = []
    for oper in operations:
        cmd, v = oper.split(' ')
        print(res)
        if cmd == 'I':
            heapq.heappush(res, int(v))
        elif res:
            if v == "-1":
                print(f"-1 origin: {res}")
                heapq.heapify(res)
                print(f"-1 heapify: {res}")
                heapq.heappop(res)
            else:
                print("1")
                heapq._heapify_max(res)
                heapq._heappop_max(res)
    return [max(res), min(res)] if res else [0, 0]
コード例 #6
0
    def findKthLargest(self, nums: List[int], k: int) -> int:

        heapq._heapify_max(nums)
        for i in range(k - 1):
            print(heapq._heappop_max(nums))

        return heapq._heappop_max(nums)
コード例 #7
0
def lastStoneWeight(A):
    heapq._heapify_max(A)
    for i in range(len(A) - 1):
        x, y = heapq._heappop_max(A), heapq._heappop_max(A)
        heapq.heappush(A, x - y)
        heapq._heapify_max(A)
    return A[0]
コード例 #8
0
def solution(operations):
    answer = []
    res = []
    for i in range(len(operations)):
        if operations[i][0] == "I":
            heapq.heappush(res, int(operations[i][2:]))
        if operations[i][0] == "D":
            if len(res) == 0:
                continue
            if operations[i][2] == "-":
                a = heapq.heappop(res)
            else:
                heapq._heapify_max(res)
                t = heapq._heappop_max(res)
                heapq.heapify(res)
    if len(res) >= 2:
        heapq._heapify_max(res)
        t = heapq._heappop_max(res)
        answer.append(t)
        heapq.heapify(res)
        answer.append(heapq.heappop(res))
    elif len(res) == 1:
        t = heapq.heapop(res)
        answer.extend((t, t))
    else:
        answer.extend((0, 0))

    return answer
コード例 #9
0
    def heap_pop(self, val):
        '''
        @pre: two balanced heaps
        @push: two balanced heaps with val removed
        :param val: the value to be removed
        removes the value by searching the proper heap
        '''
        
        if val <= self.maxH[0] and not self.maxL == 0:
            index = self.maxH.index(val)
            while index > 0:
                up = (index + 1) / 2 - 1
                self.maxH[int(index)] = self.maxH[int(up)]
                index = up

            heapq._heappop_max(self.maxH)
            self.maxL += -1
        else:
            index = self.minH.index(val)
            self.minL += -1
            while index > 0:
                up = (index + 1) / 2 - 1
                self.minH[int(index)] = self.minH[int(up)]
                index = up
            heapq.heappop(self.minH)

        self.rebalance_heaps()
        print(self.get_median())
コード例 #10
0
    def reorganizeString(self, S: str) -> str:
        map = {}
        for c in S:
            if c not in map:
                map[c] = 1
            else:
                map[c] += 1

        heap = []
        for key, value in map.items():
            heap.append(value)

        heapq._heapify_max(heap)

        first = heapq._heappop_max(heap)
        second = heapq._heappop_max(heap)
        while second > 0:
            first = -1
            second = -1
            heap.append(first)
            heap.append(second)
            heapq._heapify_max(heap)
            first = heapq._heappop_max(heap)
            second = heapq._heappop_max(heap)

        if first > 1:
            return False

        return True
コード例 #11
0
def solution(operations):
    answer = []
    heap = []
    for item in operations:
        oper = item.split()[0]
        oper_num = int(item.split()[1])
        if oper == 'I':
            heap.append(oper_num)
        else:
            if len(heap) == 0:
                continue
            elif oper_num == 1:  # 최댓값 삭제
                heapq._heapify_max(heap)
                heapq._heappop_max(heap)
            else:
                heapq.heapify(heap)
                heapq.heappop(heap)
    if len(heap) == 0:
        answer = [0, 0]
    else:
        heapq._heapify_max(heap)
        max_num = heapq._heappop_max(heap)

        heapq.heapify(heap)
        min_num = heapq.heappop(heap)
        answer = [max_num, min_num]
    return answer
コード例 #12
0
def kth_largest(num, k):
    heapq._heapify_max(num)
    while k > 1:
        heapq._heappop_max(num)
        k -= 1

    return heapq._heappop_max(num)
コード例 #13
0
ファイル: code-1046.py プロジェクト: zqfang666/learnpy
def lastStoneWeight(stones: "List[int]") -> int:
    while len(stones) >= 2:
        heapq._heapify_max(stones)
        x = heapq._heappop_max(stones)
        y = heapq._heappop_max(stones)
        if x != y:
            heapq.heappush(stones, abs(x - y))
    return stones[0] if stones else 0
コード例 #14
0
def third_max_number(nums):
    nums = list(set(nums))
    if len(nums) < 3: return max(nums)
    heapq._heapify_max(nums)

    heapq._heappop_max(nums)
    heapq._heappop_max(nums)

    return heapq._heappop_max(nums)
コード例 #15
0
 def lastStoneWeight(self, stones: List[int]) -> int:
     _heapify_max(stones)
     while len(stones) > 1:
         x = _heappop_max(stones)
         y = stones[0]
         if x == y:
             _heappop_max(stones)
         else:
             _heapreplace_max(stones, x - y)
     return stones[0] if stones else 0
コード例 #16
0
    def lastStoneWeight(self, stones) -> int:

        while len(stones) > 1:
            heapq._heapify_max(stones)
            stone_one = heapq._heappop_max(stones)
            stone_two = heapq._heappop_max(stones)
            if stone_one > stone_two:
                heapq.heappush(stones, abs(stone_two - stone_one))
        if stones: return stones.pop()
        return 0
コード例 #17
0
def kth_largest(arr, k):
    heapq._heapify_max(arr)

    k -=1
    while k:
        item = heapq._heappop_max(arr)
        
        k -=1
    
    return heapq._heappop_max(arr)
コード例 #18
0
	def getMaxKey(self) -> str:
		"""
		Returns one of the keys with maximal value.
		"""
		if not self.minmaxHeap:
			return ''
		maxItem = hq._heappop_max(self.minmaxHeap)
		while self.minmaxHeap and maxItem in self.removed:
			maxItem = hq._heappop_max(self.minmaxHeap)
		return maxItem[0]
コード例 #19
0
def solution(operations):
    heap = []
    for oper in operations:
        if oper[0] == "I":
            hq.heappush(heap, int(oper.split("I ")[1]))
        elif oper == "D -1" and len(heap) != 0:
            hq.heappop(heap)
        elif oper == "D 1" and len(heap) != 0:
            hq._heappop_max(heap)
    return ([max(heap), min(heap)] if len(heap) != 0 else [0, 0])
コード例 #20
0
def lastStoneWeight(stones):
    heapq._heapify_max(stones)

    while len(stones) > 1:
        maxStone = heapq._heappop_max(stones)
        secStone = heapq._heappop_max(stones)
        if maxStone >= secStone:
            heapq.heappush(stones, maxStone - secStone)
        heapq._heapify_max(stones)

    print(stones[0])
コード例 #21
0
ファイル: B.py プロジェクト: luliu31415926/google_code_jam
def solve(Ac, Aj, Ac_lst, Aj_lst):
    lst = []
    for s, e in Ac_lst:
        lst.append([s, e, 0])
    for s, e in Aj_lst:
        lst.append([s, e, 1])
    lst.sort()
    c_inside_intervals = []
    j_inside_intervals = []
    stack = [lst[0]]
    cnt = 0
    for s, e, p in lst[1:]:
        if p != stack[-1][-1]:
            # different person
            cnt += 1
            stack.append([s, e, p])
        else:
            # same person, collapse interval
            pre_s, pre_e, pre_p = stack.pop()
            if p == 0:
                c_inside_intervals.append(s - pre_e)
            if p == 1:
                j_inside_intervals.append(s - pre_e)
            stack.append([pre_s, e, p])

    # check midnight switch
    if stack[0][-1] == stack[-1][-1]:
        inside_interval = stack[0][0] + 1440 - stack[-1][1]
        if stack[0][-1] == 0: c_inside_intervals.append(inside_interval)
        else: j_inside_intervals.append(inside_interval)
        stack[0][0] = 0
        stack[-1][1] = 1440
    else:
        cnt += 1

    #print (stack,cnt)
    heapq._heapify_max(c_inside_intervals)
    heapq._heapify_max(j_inside_intervals)
    c_total, j_total = 0, 0
    for s, e, p in stack:
        if p == 0: c_total += (e - s)
        if p == 1: j_total += (e - s)
    while c_total > 12 * 60:
        split_interval = heapq._heappop_max(c_inside_intervals)
        cnt += 2
        c_total -= split_interval
        #print ('splinting c interval',split_interval)
    while j_total > 12 * 60:
        split_interval = heapq._heappop_max(j_inside_intervals)
        cnt += 2
        j_total -= split_interval
        #print ('splinting j interval',split_interval)

    return cnt
コード例 #22
0
ファイル: 976.py プロジェクト: VittorioYan/Leetcode-Python
 def largestPerimeter(self, A: List[int]) -> int:
     if len(A) < 3:
         return 0
     heapq._heapify_max(A)
     biggest, a, b = heapq._heappop_max(A), heapq._heappop_max(A), 0
     while A:
         b = heapq._heappop_max(A)
         if a + b <= biggest:
             biggest, a, b = a, b, 0
         else:
             return a + b + biggest
     return 0
コード例 #23
0
    def lastStoneWeight(self, stones: List[int]) -> int:
        heapq._heapify_max(stones)
        while (len(stones) > 1):
            x = heapq._heappop_max(stones)
            y = heapq._heappop_max(stones)
            if x != y:
                stones.append(x - y)
                heapq._heapify_max(stones)

        if len(stones) == 0:
            return 0
        return stones[0]
コード例 #24
0
    def lastStoneWeight(self, stones: List[int]) -> int:

        while stones:
            heapq._heapify_max(stones)
            if len(stones) == 1:
                return heapq._heappop_max(stones)

            heapq.heappush(
                stones,
                heapq._heappop_max(stones) - heapq._heappop_max(stones))

        return 0
コード例 #25
0
def k_most_freq(input):
    count = defaultdict(lambda: 0)
    for x in input:
        count[x] += 1

    list_of_vals = []
    for k in count.keys():
        heapq.heappush(list_of_vals, k)
        if len(list_of_vals) > N:
            heapq._heappop_max(list_of_vals)

    return list_of_vals
コード例 #26
0
 def findContentChildren(self, g: List[int], s: List[int]) -> int:
     if len(g) == 0 or len(s) == 0: return 0
     _heapify_max(g)
     _heapify_max(s)
     greed, size, count = _heappop_max(g), _heappop_max(s), 0
     while True:
         if size >= greed:
             count += 1
             if len(s) == 0: return count
             size = _heappop_max(s)
         if len(g) == 0: return count
         greed = _heappop_max(g)
コード例 #27
0
ファイル: w2_05.py プロジェクト: cocm1324/algo
	def lsw(self, stones) -> int:
		_1, _2 = 0, 0
		l = stones.copy()
		heapq._heapify_max(l)
		while len(l) > 1:
			_1 = heapq._heappop_max(l)
			_2 = heapq._heappop_max(l)
			if _1 != _2:
				l.append(_1 - _2)
				heapq._heapify_max(l)
		if len(l) == 1:
			return l[0]
		return 0
コード例 #28
0
def test(marks):
    diff = 0
    heapq._heapify_max(marks)
    while len(marks) > 1:
        popped_elm_1 = heapq._heappop_max(marks)
        popped_elm_2 = heapq._heappop_max(marks)
        diff = popped_elm_1 - popped_elm_2
        if diff > 0:
            marks.append(diff)
            heapq._heapify_max(marks)
            diff = 0
    final_elem = heapq._heappop_max(marks)
    result = final_elem - diff
    return result
コード例 #29
0
    def kClosest(self, points, K):
        def _heappush_max(heap, item):
            heap.append(item)
            heapq._siftdown_max(heap, 0, len(heap) - 1)

        heap = []
        heapq._heapify_max(heap)
        for point in points:
            distance = math.sqrt(point[0]**2 + point[1]**2)
            _heappush_max(heap, (distance, point))
            if len(heap) > K:
                heapq._heappop_max(heap)

        return [x[1] for x in heap]
コード例 #30
0
    def lastStoneWeight(self, stones: List[int]) -> int:
        heap = stones
        heapq._heapify_max(heap)
        print(heap)
        while len(heap) > 1:
            stoneOne = heapq._heappop_max(heap)
            stoneTwo = heapq._heappop_max(heap)

            if stoneOne != stoneTwo:
                heapq.heappush(heap, stoneOne - stoneTwo)

            heapq._heapify_max(heap)

        return 0 if len(heap) == 0 else heapq._heappop_max(heap)
コード例 #31
0
def balance(leftmaxq, rightminq):
    if len(leftmaxq) - len(rightminq) == 2:
        temp = heapq._heappop_max(leftmaxq)
        heapq.heappush(rightminq, temp)
    if len(rightminq) - len(leftmaxq) == 2:
        temp = heapq.heappop(rightminq)
        heapq.heappush(leftq, temp)
コード例 #32
0
ファイル: getStats.py プロジェクト: gyul1/TextAnalysis
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
コード例 #33
0
ファイル: getStats.py プロジェクト: gyul1/TextAnalysis
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
コード例 #34
0
"""
    https://www.hackerrank.com/challenges/fraudulent-activity-notifications


"""

import heapq

leftq = [10, 9, 11, 8, 12, 7, 13, 6]

# heapq.heapify(leftq)
heapq._heapify_max(leftq)
while leftq:
    print(heapq._heappop_max(leftq))
# print(leftq)
コード例 #35
0
ファイル: queue.py プロジェクト: fischerling/WRMS
 def pop(self):
     """Remove and return the first song from the queue"""
     if len(self.queue) > 0:
         return heapq._heappop_max(self.queue)
     else:
         return None