Ejemplo n.º 1
0
 def addSpot(self, floor, spot):
     #create spot by inserting in heap
     if floor > self.maxFloors or spot > self.spotsPerFloor:
         print("Value out of bounds")
     else:
         newSpot = ParkingSpot(floor, spot)
         insert(self.heap, newSpot)
Ejemplo n.º 2
0
    def nthUglyNumber(self, n: int) -> int:

        #   edge case check
        if (n == 1):
            return n

        #   initializations
        minHeap = [1]
        visited = set([1])
        count = 0
        primes = [2, 3, 5]
        poppedElement = 1

        #   iterate until nth ugly number
        while (count < n):

            #   remove min element from min heap
            poppedElement = remove(minHeap)
            count += 1

            #   for each of the primes, mutlipy min element and push into heap if not in the hash set
            for prime in primes:

                nextElement = poppedElement * prime

                if (nextElement not in visited):
                    visited.add(nextElement)
                    insert(minHeap, nextElement)

        #   return the nth popped element from min heap
        return poppedElement
Ejemplo n.º 3
0
    def run(self):
        user_priority_q = []
        post_q = []

        for i in range(self.number_of_users):
            username = get_random_string(16)
            user_bot = UserBot(username=username, password='******', email=username+'@close.io')
            insert(user_priority_q, (i, user_bot.number_of_posts, user_bot))
            post_q.append(user_bot.posts)

        while user_priority_q and post_q:
            user_bot = extract_maximum(user_priority_q)[-1]
            user_finished = False

            while user_priority_q and not user_finished and post_q and user_bot.number_of_likes:
                posts = post_q.pop()

                if not user_bot.posts.intersection(posts):
                    for _ in range(min([user_bot.number_of_likes, len(posts)])):
                        user_bot.make_like(posts.pop())

                if not post_q:
                    user_finished = True

                if posts:
                    post_q.append(posts)
Ejemplo n.º 4
0
def a_star(state):
    """ algorithm A* """
    ideal = '123456789ABCDEF0'
    if not have_a_solve(state):
        print('No solution!')
        return []
    h = get_heuristic(state)
    g = 0
    node = Node(f=get_f(g, h), value=state, parent=None, g=g, h=h)
    pq = []         # priority queue
    insert(pq, node)
    res = list()    # list of result way
    close = set()
    while pq:
        cur = extract(pq)  # extract last node
        if cur.value == ideal:
            print('Success!')
            g = cur.g
            res.append(cur.value)
            while cur.parent:
                res.append(cur.parent.value)
                cur = cur.parent
            res.reverse()
            return res, g

        if cur.value not in close:
            close.add(cur.value)
            # add 4 ways to queue
            ways = [up(cur.value), right(cur.value), down(cur.value), left(cur.value)]
            for way in ways:
                if way:
                    h = get_heuristic(way)
                    g = cur.g + 1
                    node = Node(f=get_f(g, h), value=way, parent=cur, g=g, h=h)
                    insert(pq, node)
Ejemplo n.º 5
0
    def lastStoneWeight(self, stones: List[int]) -> int:

        #   Time:   O(NlogN + N/2logN) ~ O(NlogN)
        #   Space:  O(N) for maxHeap

        #   initializations
        maxHeap = []

        #   filling maxHeap with -1 times the actual value
        for i in range(len(stones)):
            insert(maxHeap, -stones[i])

        #   remove last 2 elements (as numbers are negative an we have only minHeap in py)
        while (len(maxHeap) > 1):
            first = remove(maxHeap)
            second = remove(maxHeap)

            #   if equal => don't do anything and continue the loop
            if (first == second):
                continue

            #   otherwise insert -1 times the absolute value of top 2 numbers
            insert(maxHeap, -1 * abs(first - second))

        #   if one element present => take out the absolute value
        #   else return 0
        if (len(maxHeap) == 1):
            return (-1 * remove(maxHeap))
        else:
            return 0
Ejemplo n.º 6
0
    def addParkingSpace(self, floor: int, slot: int) -> None:

        parkingSpace = ParkingSpace(floor, slot)

        #   if parking space is in limitations => add it to the available slots in priority queue
        if (floor < self.__maxFloors and slot < self.__maxSlots):
            insert(self.__priorityQueue, parkingSpace)
        #   else do nothing
        else:
            print('Try another Floor and another Slot !!!')
Ejemplo n.º 7
0
 def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
     heap = []
     result = []
     for p in points:
         dist = -(p[0]**2 + p[1]**2)
         insert(heap, [dist, p])
         if len(heap) > K:
             remove(heap)
     for i in heap:
         result.append(i[1])
     return result
    def __init__(self, k: int, nums: List[int]):

        #   initialize in such a way that your Data Structure has only k largest elements
        self.minHeap = []
        self.capacity = k

        for num in nums:
            insert(self.minHeap, num)

            if (len(self.minHeap) > k):
                remove(self.minHeap)
Ejemplo n.º 9
0
def main():
    string = input()
    dictionary = {}

    # считываем символы и их частоты
    for ch in string:
        if ch in dictionary.keys():
            dictionary[ch] += 1
        else:
            dictionary[ch] = 1

    # добавляем символы в очередь, используя частоту в качестве приоритета
    pq = []
    ident = 0
    for ch in dictionary:
        priority = dictionary.get(ch)
        insert(pq, (priority, ident, ch))
        ident += 1
        dictionary[ch] = ''

    if len(pq) == 1:
        dictionary[pq[0][2]] = '0'
    else:
        # создаем узлы дерева
        while len(pq) > 1:
            min1 = extract_min(pq)
            min2 = extract_min(pq)

            if type(min1[2]) is str:
                leaf1 = Tree(min1[2], min1[0])
            else:
                leaf1 = min1[2]
            if type(min2[2]) is str:
                leaf2 = Tree(min2[2], min2[0])
            else:
                leaf2 = min2[2]

            F = Tree(None, leaf1.freq + leaf2.freq, right=leaf2, left=leaf1)
            insert(pq, (F.freq, ident, F))

            ident += 1

        F.freq = None
        creating_code(dictionary, F)

    encoded_string = ''
    for ch in string:
        encoded_string += dictionary[ch]

    print(f'{len(dictionary)} {len(encoded_string)}')
    for i in dictionary:
        print(f'{i}: {dictionary[i]}')
    print(encoded_string)
Ejemplo n.º 10
0
    def leastInterval(self, tasks: List[str], n: int) -> int:

        #   initializations
        frequencyMap = {}
        T = len(tasks)
        maxHeap = []
        time = 0

        #   fill frequency map
        for task in tasks:
            if task in frequencyMap:
                frequencyMap[task] += 1
            else:
                frequencyMap[task] = 1

        #   insert all frequency map info into the Heap
        for char in frequencyMap:
            charFreq = FrequencyMap(char, frequencyMap[char])
            insert(maxHeap, charFreq)

        #   iterate until nothing is left in Heap
        while (len(maxHeap) > 0):

            #   to calculate cooldown time
            tempTime = 0
            bufferList = []

            #   iterate cooldown time ends
            while (tempTime <= n):

                #   If any element in Heap
                if (len(maxHeap) > 0):
                    maxCharFreq = maxHeap[0]
                    if (maxCharFreq.freq > 1):  #   if frequency > 1
                        maxCharFreq.freq -= 1
                        bufferList.append(maxCharFreq)  #   add to buffer list
                    remove(maxHeap)  #   remove max element anyway

                time += 1  #   increment overall time

                #   if nothing exists in both Heap and buffer list => we're done
                if (len(maxHeap) == 0 and len(bufferList) == 0):
                    break

                #   increment twmp time until <= cooldown time
                tempTime += 1

            #   now after cooldown, add each entry from Buffer list to Max Heap
            for eachEntry in bufferList:
                insert(maxHeap, eachEntry)

        #   return overall time
        return time
Ejemplo n.º 11
0
 def getValues(self, countMap):
     heap = []
     for key in countMap:
         count = countMap[key]
         p = Pair(key, count)
         insert(heap, p)
         if len(heap) > 3:
             remove(heap)
     stack = []
     while len(heap) > 0:
         stack.append(remove(heap).sentence)
     return stack[::-1]
Ejemplo n.º 12
0
 def minMeetingRooms(self, intervals):
     if not intervals:
         return 0
     heap = []
     intervals = sorted(intervals, key=lambda interval: interval.start)
     for i in intervals:
         if len(heap) == 0:
             insert(heap, i.end)
             continue
         if i.start >= heap[0]:
             remove(heap)
         insert(heap, i.end)
     return len(heap)
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:

        minHeap = []

        #   once the size overloads => remove the max element from the heap
        for point in points:

            newPoint = Point(point)
            insert(minHeap, newPoint)

            if (len(minHeap) > K):
                remove(minHeap)

        return [each.point for each in minHeap]
Ejemplo n.º 14
0
    def add(self, val: int) -> int:

        #   first insert the new value and if size exceeds => remove the min value
        insert(self.minHeap, val)

        if (len(self.minHeap) > self.capacity):
            remove(self.minHeap)

        #   kth largest would be == first element
        return self.minHeap[0]


# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
Ejemplo n.º 15
0
def main():
    k, l = map(int, input().split())    # количество различных букв в строке, размер получившейся закодированной строки
    _dict = {}
    for i in range(k):
        _str = input()
        _dict[_str[3:]] = _str[0]
    encoded_string = input()

    pq = []
    for ch in _dict:
        code = [i for i in ch]
        insert(pq, (code, _dict[ch]))

    root = create_decode_tree(pq)
    print(decoding(encoded_string, root))
Ejemplo n.º 16
0
 def getNewsFeed(self, userId: int) -> List[int]:
     """
     Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
     """
     q = []
     followers = self.UserMap[userId]
     followers.add(userId)
     for f in followers:
         for tweet in self.TweetsMap[f]:
             t, post = tweet[0], tweet[1]
             if len(q) < 10:
                 insert(q, (t, post))
             elif t > q[0][0]:
                 remove(q)
                 insert(q, (t, post))
     result = []
     while q:
         t, post = remove(q)
         result.append(post)
     return result[::-1]
Ejemplo n.º 17
0
    def getNewsFeed(self, userId: int) -> List[int]:
        """
        Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
        """
        self._newUser(userId)
        tweet_list = []
        followedUsers = self.user_follower[userId]
        if followedUsers:
            for followee in followedUsers:
                if followee in self.user_tweet and len(
                        self.user_tweet[followee]) > 0:
                    for tweet in self.user_tweet[followee]:
                        insert(tweet_list, tweet)
                        if len(tweet_list) > self.feed_limit:
                            remove(tweet_list)

        output = []
        while len(tweet_list) > 0:
            output.append(remove(tweet_list).tweetId)

        return output[::-1]
Ejemplo n.º 18
0
def calculate_dijkstra(graph: Graph, source: int) -> Dict[int, Dict[str, Any]]:
    result = {node: {COST: inf, ARC: None, VISITED: False} for node in graph}
    result[source][COST] = 0

    to_visit = []
    insert(to_visit, (0, source))

    while len(to_visit) > 0:
        to_open = extract_minimum(to_visit)[1]
        if result[to_open][VISITED]:
            continue
        result[to_open][VISITED] = True

        for arc in graph[to_open][OUT_ARCS]:
            new_cost = result[to_open][COST] + arc.info[WEIGHT]
            if result[arc.dest][COST] > new_cost:
                result[arc.dest][COST] = new_cost
                result[arc.dest][ARC] = arc.index
                insert(to_visit, (new_cost, arc.index))

    return result
Ejemplo n.º 19
0
    def __getTopK(self, frequencyMap):

        #   initialize Heap
        minHeap = []

        #   for each sentence, maintain top K sentences seen so far
        for sent in frequencyMap:
            frequency = frequencyMap[sent]
            currentObject = FrequencyMap(sent, frequency)

            if (len(minHeap) == self.k):
                minObject = remove(minHeap)

                if (currentObject > minObject):
                    insert(minHeap, currentObject)
                else:
                    insert(minHeap, minObject)

            else:
                insert(minHeap, currentObject)

        #   put the remaining top K sentences in a stack for extracting them in descending order
        stack = []
        while (len(minHeap) > 0):
            currentObject = remove(minHeap)
            stack.append(currentObject.sentence)

        #   add to the final list of sentences in descending order
        finalList = []
        while (len(stack) > 0):
            finalList.append(stack.pop())

        #   return the top K sentences
        return finalList
Ejemplo n.º 20
0
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:

        #   edge case checks
        if (nums == None or len(nums) == 0):
            return []

        #   initializations
        finalResult = [0 for i in range(k)]

        frequencyMap = {}
        minHeap = []

        #   calculate number-count HashMap and then convert to custom class pairs while pushing into Heap
        for num in nums:

            if num not in frequencyMap:
                frequencyMap[num] = 1
            else:
                frequencyMap[num] += 1

        #   for each number in the Map
        for number in frequencyMap:

            #   create the pair class object
            currentPair = NumberFrequencyPair(number, frequencyMap[number])

            #   insert the element
            insert(minHeap, currentPair)

            #   if size exceeds k => remove the minimum frequent element
            if len(minHeap) > k:
                remove(minHeap)

        #   now, put all top k frequent elements in correct locations (in reverse directions as it is a min heap)
        for i in range(k - 1, -1, -1):
            poppedPair = remove(minHeap)
            finalResult[i] = poppedPair.getNumber()

        #   return the final result
        return finalResult
Ejemplo n.º 21
0
    def findMinNoOfMeetingRooms(self, intervals: list) -> int:

        #   edge case check
        if (intervals == None or len(intervals) == 0):
            return 0

        #   sort the array based on start times
        intervals.sort(key=lambda x: x.start)

        #   initialize minHeap with one element
        minHeap = [intervals[0]]

        #   first check the min end time of elements using minHeap
        #   if next element in sorted array has end time less than min end time => overlapping => add to minHeap
        #   else remove min end time element as no other interval clashes
        for i in range(1, len(intervals)):
            minEnd = minHeap[0].end
            if (intervals[i].start >= minEnd):
                remove(minHeap)
            insert(minHeap, intervals[i])

        #   return the count left in minHeap as those many rooms will be required.
        return len(minHeap)
Ejemplo n.º 22
0
def calculate_dijkstra(source: int, layered_graph: LayeredGraph, ) -> Tuple[MultiDiGraph, MultiDiGraph]:
    node_info = {node: {COST: inf, ARC: None, VISITED: False, DEPTH: inf} for node in layered_graph}
    node_info[source][COST] = 0
    node_info[source][DEPTH] = 0
    tree = MultiDiGraph()

    to_visit = []
    insert(to_visit, (0, source))
    images = {node: [] for node in layered_graph.origin_nodes}
    insert(images[layered_graph.origin_node_index(source)], ((0, 0), source))
    leafs = set()

    while len(to_visit) > 0:
        to_open = extract_minimum(to_visit)[1]
        if node_info[to_open][VISITED]:
            continue
        node_info[to_open][VISITED] = True

        for arc in layered_graph.out_edges(to_open, data=True):
            dest = arc[1]
            if not layered_graph.out_edges(dest):
                leafs.add(dest)
            new_cost = node_info[to_open][COST] + arc[2][WEIGHT]
            new_depth = node_info[to_open][DEPTH] + 1
            if node_info[dest][COST] > new_cost:
                node_info[dest][COST] = new_cost
                node_info[dest][ARC] = arc
                node_info[dest][DEPTH] = new_depth
                insert(to_visit, (new_cost, dest))
                insert(images[layered_graph.origin_node_index(dest)], ((new_cost, new_depth), dest))
                if tree.has_edge(to_open, dest):  # TODO change on link to arc
                    tree.remove_edge(to_open, dest)
                tree.add_edge(to_open, dest, COST=new_cost)

    # node_info truncation - усечение дерева
    not_truncated_tree = MultiDiGraph(tree)
    while leafs:
        leaf = leafs.pop()
        path_cost = node_info[leaf][COST]
        path_depth = node_info[leaf][DEPTH]
        if nsmallest(1, images[layered_graph.origin_node_index(leaf)]) != ((path_cost, path_depth), leaf):
            parent = node_info[leaf][ARC][0]
            tree.remove_node(leaf)
            if not tree.out_edges(parent):
                leafs.add(parent)

    return tree, not_truncated_tree
Ejemplo n.º 23
0
 def addNum(self, num: int) -> None:
     
     #   if upper half min heap is empty or current element is greater than its min (=> current element's place 
     #   is definitely in upper half whereas not sure about the heap's min element).
     if ( len(self.upperHalfMinHeap) == 0 or num > self.upperHalfMinHeap[0] ):
         insert(self.upperHalfMinHeap, num)
     
     else:
         insert(self.lowerHalfMaxHeap, -num)
     
     #   re-balance according to the sizes   
     while ( abs(len(self.upperHalfMinHeap) - len(self.lowerHalfMaxHeap)) >= 2):
         
         if (len(self.upperHalfMinHeap) > len(self.lowerHalfMaxHeap)):
             number = remove(self.upperHalfMinHeap)
             insert(self.lowerHalfMaxHeap, -number)
             
         else:
             number = remove(self.lowerHalfMaxHeap)
             insert(self.upperHalfMinHeap, -number)
Ejemplo n.º 24
0
 def nthUglyNumber(self, n: int) -> int:
     hashset = set()
     heap = []
     heapq.heappush(heap, 1)
     hashset.add(1)
     
     for i in range(n-1):
         curr = remove(heap)
         n2 = 2 * curr
         n3 = 3 * curr
         n5 = 5 * curr
         if n2 not in hashset:
             hashset.add(n2)
             insert(heap, n2)
         if n3 not in hashset:
             hashset.add(n3)
             insert(heap, n3)
         if n5 not in hashset:
             hashset.add(n5)
             insert(heap, n5)
     return remove(heap)
Ejemplo n.º 25
0
from heapq import heappush as insert, heappop as extract_maximum
pq = []

insert(pq, 4)

insert(pq, 2)
insert(pq, 3)
insert(pq, 1)

print(extract_maximum(pq))
print(extract_maximum(pq))
print(extract_maximum(pq))
print(extract_maximum(pq))