def solveGreedy(game, over, dir):
    estimation = manhattanDistance(game, over)
    max = 0
    caminho[AuxFunctions.returnString(game)] = AuxFunctions.returnString(game)
    distancias = []
    # Implementacao de heap em ordem das distancias
    heapq.heapify(distancias)
    heapq.heappush(distancias, (estimation, game))
    while not len(distancias) == 0:
        node = heapq.heappop(distancias)
        repetidos[AuxFunctions.returnString(node[1])] = 1
        index = node[1].index(0)
        for value in dir[index]:
            # Troca de elementos, acedendo a segunda posicao do tuplo
            node1 = node[1][:]
            node1[index + value], node1[index] = node1[index], node1[index + value]
            node1String = AuxFunctions.returnString(node1)
            if not caminho.get(node1String):
                caminho[node1String] = AuxFunctions.returnString(node[1])
            dis = manhattanDistance(node1, over)
            if dis == 0:
                print "Tiveram em dada altura um maximo de", max, "nos na fila."
                return node
            if not repetidos.get(node1String):
                heapq.heappush(distancias, (dis, node1[:]))
                if len(distancias) > max:
                    max = len(distancias)
示例#2
0
def _cases(doc, form):
    if isinstance(form, String):
        generators = [_forms.get(form.get_string_value())]
    elif form.get_head_name() == 'System`Alternatives':
        if not all(isinstance(f, String) for f in form.leaves):
            return  # error
        generators = [_forms.get(f.get_string_value()) for f in form.leaves]
    elif form.get_head_name() == 'System`Containing':
        if len(form.leaves) == 2:
            for t in _containing(doc, *form.leaves):
                yield t
            return
        else:
            return  # error
    else:
        return  # error

    def try_next(iterator):
        try:
            return next(iterator)
        except StopIteration:
            return None

    feeds = []
    for i, iterator in enumerate([iter(generator(doc)) for generator in generators]):
        t = try_next(iterator)
        if t:
            feeds.append((_position(t), i, t, iterator))
    heapq.heapify(feeds)
    while feeds:
        pos, i, token, iterator = heapq.heappop(feeds)
        yield token
        t = try_next(iterator)
        if t:
            heapq.heappush(feeds, (_position(t), i, t, iterator))
示例#3
0
文件: pools.py 项目: MapofLife/MOL
    def imerge(iterables):
        """Merge-sorts items from a list of iterators.
        """

        _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration

        h = []
        h_append = h.append
        for itnum, it in enumerate(map(iter, iterables)):
            try:
                next = it.next
                h_append([next(), itnum, next])
            except _StopIteration:
                pass
        heapify(h)

        while 1:
            try:
                while 1:
                    v, itnum, next = s = h[0]   # raises IndexError when h is empty
                    yield v
                    s[0] = next()               # raises StopIteration when exhausted
                    _heapreplace(h, s)          # restore heap condition
            except _StopIteration:
                _heappop(h)                     # remove empty iterator
            except IndexError:
                return
示例#4
0
文件: server.py 项目: tommie/rsyba
    def _merge_file_iters(self, iters, key=lambda x: x):
        heap = []
        for iter, root in iters:
            try:
                heap.append((next(iter), iter, root))
            except StopIteration:
                pass

        heapq.heapify(heap)
        while heap:
            value, iter, root = heapq.heappop(heap)
            try:
                heapq.heappush(heap, (next(iter), iter, root))
            except StopIteration:
                pass

            items = [(value, root)]
            while heap:
                cand, iter, root = heapq.heappop(heap)
                if key(cand) == key(value):
                    items.append((cand, root))
                    try:
                        heapq.heappush(heap, (next(iter), iter, root))
                    except StopIteration:
                        pass
                else:
                    heapq.heappush(heap, (cand, iter, root))
                    break

            yield items
示例#5
0
文件: awj.py 项目: tacaswell/awj
 def __getitem__(self, key):
     fn = self._fn_cache[key]
     ret = feather.read_dataframe(fn)
     self._heap_map[key][0] = time.time()
     # ensure the heap invariant
     heapq.heapify(self._heap)
     return ret
def Min_Span_Tree(outside_tree):
    #find all edges & put into a priorityQ
    heap = []
    for pair in itertools.combinations(outside_tree, 2):
        heapq.heappush(heap, (Edge(pair), pair))

    inside_tree = set()
    answer = 0
    heapq.heapify(list(outside_tree))
    initial = outside_tree.pop()

    while outside_tree:
        inside_tree.update(initial)

        shortest = min([item for item in heap if initial in item[1]])
        answer += float(shortest[0])
        x, y = shortest[1]
        inside_tree.update(x, y)
        heap.remove(shortest)

        next_point = outside_tree.pop()

        initial = next_point

    return answer
示例#7
0
def imerge(*iterables):
    """
    Merge multiple sorted inputs into a single sorted output.

    Equivalent to:  sorted(itertools.chain(*iterables))

    >>> list(imerge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
    [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
    """
    heappop, siftup, _StopIteration = heapq.heappop, heapq._siftup, StopIteration

    h = []
    h_append = h.append
    for it in map(iter, iterables):
        try:
            _next = it.next
            h_append([_next(), _next])
        except _StopIteration:
            pass
    heapq.heapify(h)

    while 1:
        try:
            while 1:
                v, _next = s = h[0]     # raises IndexError when h is empty
                yield v
                s[0] = _next()          # raises StopIteration when exhausted
                siftup(h, 0)            # restore heap condition
        except _StopIteration:
            heappop(h)                  # remove empty iterator
        except IndexError:
            return
示例#8
0
    def _run_until_current(self):
        self._insert_new_calledlaters()
        now = time.time()
        while self._pending_timed_calls and (self._pending_timed_calls[0].time <= now):
            call = heapq.heappop(self._pending_timed_calls)
            if call.cancelled:
                self._cancellations -= 1
                continue

            if call.delayed_time > 0:
                call.activate_delay()
                heapq.heappush(self._pending_timed_calls, call)
                continue

            try:
                call.called = 1
                call.func(*call.args, **call.kw)
            except _reraised_exceptions:
                raise
            except:
                getlog().exception("CallLater failed")

        if self._cancellations > 50 and self._cancellations > len(self._pending_timed_calls) >> 1:
            self._cancellations = 0
            self._pending_timed_calls = [x for x in self._pending_timed_calls if not x.cancelled]
            heapq.heapify(self._pending_timed_calls)
    def create_binary_tree(self):
        """
        Create a binary Huffman tree using stored vocabulary word counts. Frequent words
        will have shorter binary codes. Called internally from `build_vocab()`.

        """
        logger.info("constructing a huffman tree from %i words" % len(self.vocab))

        # build the huffman tree
        heap = self.vocab.values()
        heapq.heapify(heap)
        for i in xrange(len(self.vocab) - 1):
            min1, min2 = heapq.heappop(heap), heapq.heappop(heap)
            heapq.heappush(heap, Vocab(count=min1.count + min2.count, index=i + len(self.vocab), left=min1, right=min2))

        # recurse over the tree, assigning a binary code to each vocabulary word
        if heap:
            max_depth, stack = 0, [(heap[0], [], [])]
            while stack:
                node, codes, points = stack.pop()
                if node.index < len(self.vocab):
                    # leaf node => store its path from the root
                    node.code, node.point = codes, points
                    max_depth = max(len(codes), max_depth)
                else:
                    # inner node => continue recursion
                    points = array(list(points) + [node.index - len(self.vocab)], dtype=uint32)
                    stack.append((node.left, array(list(codes) + [0], dtype=uint8), points))
                    stack.append((node.right, array(list(codes) + [1], dtype=uint8), points))

            logger.info("built huffman tree with maximum node depth %i" % max_depth)
示例#10
0
def k_smallest_matrix(matrix, k):
    """
    Given a n x n matrix where each of the rows and columns are sorted in ascending order,
    find the kth smallest element in the matrix.

    :param matrix: A square matrix of size n x n in sorted order for its rows and cols
    :param k: The kth-smallest element to look for

    :return: An k-th smallest element in the matrix.
    """

    # Take the entire first row and heapify it
    open_list = [(matrix[y][x], y, x) for x in xrange(len(matrix)) for y in xrange(len(matrix))]
    heapq.heapify(open_list)
    current_min = None

    # Take the min element and enqueue the element below it if possible; when k is 0 we have our k'th min element
    while k != 0:
        current_min, current_y, current_x = heapq.heappop(open_list)

        if y < len(matrix):
            heapq.heappush(open_list, (matrix[y][x], current_y, current_x))

        k -= 1
    return current_min
    def __init__(self, heap=[]):
        """if 'heap' is not empty, make sure it's heapified"""

        heapq.heapify(heap)
        self.heap = heap
        self.entry_finder = dict({i[-1]: i for i in heap})
        self.REMOVED = '<remove_marker>'
	def test_buscar_el_mayor_y_menor_valor_de_una_lista(self):
		import heapq
		nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

		tres_mayores = heapq.nlargest(3,nums) 
		self.assertEqual(tres_mayores,[42,37,23])
		tres_menores = heapq.nsmallest(3,nums)
		self.assertEqual(tres_menores,[-4,1,2])

		mayor = max(nums)
		menor = min(nums)
		self.assertEqual(mayor ,42)
		self.assertEqual(menor ,-4)

		heap = list(nums)
		#Pone el primer elemento en la posicion 0
		heapq.heapify(heap)
		self.assertEqual(heap,[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8])

		#heappop saca el primer elemento, y lo sustituye por el menor de la lista
		# asi heappop siempre sacara el elemento mas pequeño
		menor =heapq.heappop(heap)
		self.assertEqual(menor,-4)
		menor =heapq.heappop(heap)
		self.assertEqual(menor, 1)	
示例#13
0
  def trapRainWater(self, heightMap):
    if not heightMap: return 0

    import heapq
    m, n = len(heightMap), len(heightMap[0])
    queue, vis, res = [], [[False]*n for _ in range(m)], 0
    for i in range(m):
      queue.append((heightMap[i][0], (i,0)))
      queue.append((heightMap[i][n-1], (i,n-1)))
      vis[i][0] = vis[i][n-1] = True
    for i in range(1,n-1):
      queue.append((heightMap[0][i], (0,i)))
      queue.append((heightMap[m-1][i], (m-1,i)))
      vis[0][i] = vis[m-1][i] = True
    heapq.heapify(queue)
    while queue:
      val, loc = heapq.heappop(queue)
      res += val - heightMap[loc[0]][loc[1]]
      for d in [[-1,0],[0,1],[1,0],[0,-1]]:
        tx, ty = loc[0]+d[0], loc[1]+d[1]
        if 0 < tx < m and 0 < ty < n and not vis[tx][ty]:
          vis[tx][ty] = True
          heapq.heappush(queue, (max(val, heightMap[tx][ty]), (tx, ty)))

    return res
def skyline(buildings):
    if not buildings:
        return []
    points = []
    for l, r, h in buildings:
        points.append([l, -h])
        points.append([r, h])
    # sort the points to ensure that all points are sorted from left to right
    points.sort()
    result = []
    queue = [0]
    prev = 0
    for e in points:
        if e[1] < 0:
            # whenever we see start point of the building
            # we put the height of the building into the heapq
            heapq.heappush(queue, e[1])
        else:
            # if we arrive at the end point of the building
            # we remove the height of the building from the heapq
            if queue[0] == -e[1]:
                heapq.heappop(queue)
            else:
                queue.remove(-e[1])
                heapq.heapify(queue)
        curr = queue[0]
        if curr != prev:
            # if the tallest building in the heapq changes
            # then we need to put that into the final result
            result.append([e[0], -curr])
            prev = curr
    return result
示例#15
0
文件: friar.py 项目: jefk/billfriar
 def __init__(self, ls = []):
     ''' ls is a list of tuples in this format
         [ (val, label), (val, label), ... ]
     '''
     # multiply val by -1 to make this into a max heap, heapq is min heap
     self.heap = [ [-1 * val, label] for val, label in ls ]
     heapq.heapify(self.heap)
示例#16
0
    def remove_at(self, index):
        """Removes item at given index"""

        with self.lock:
            item = self.items.pop(index)[0]
            heapq.heapify(self.items)
        return item
示例#17
0
def prim_std(G):
    """Input: A connected undirected graph G=(V, E) with edge weights
Output: A minimum spanning tree defined by the dict prev
This prim uses heapq in standard library, with 3 times faster than prim(G).
    """
    V, E = G
    cost = {}
    prev = {}
    for u in V:
        cost[u] = float("inf")
        prev[u] = None
    cost[V[0]] = 0
    H = [(cost[u], u) for u in V]
    heapify(H)
    while len(H):
        costv, v = heappop(H)
        for z in E[v]:
            weightVZ = E[v][z]
            if cost[z] > weightVZ:
                try:
                    indexZ = H.index((cost[z], z))
                except ValueError:
                    continue
                cost[z] = weightVZ
                prev[z] = v
                print  "From <%d> to <%d> cost: %d" % (v,z,weightVZ)
                H[indexZ] = (cost[z], z)
                heapify(H)
    return prev
示例#18
0
 def iterate (self):
     
     if not len (self.open):
         return False
     
     self.solution = heapq.heappop (self.open)
     self.waypoints.remove (self.solution)
     
     if self.solution.can_see_goal:
         return True
     
     for waypoint in self.waypoints:
         
         if self.solution.dists[waypoint] == -1.0:
             continue
         
         new_g = self.solution.g_cost + self.solution.dists[waypoint]
         
         if waypoint in self.open and new_g >= waypoint.g_cost:
             continue
         
         waypoint.g_cost = new_g
         waypoint.f_cost = waypoint.g_cost + waypoint.h_cost
         waypoint.parent = self.solution
         
         if waypoint.can_see_goal:
             self.solution = waypoint
             return True
         
         if waypoint not in self.open:
             # At this point, the heap invariant may be violated, so who
             # knows how much better this is than just appending it
             heapq.heappush (self.open, waypoint)
     
     heapq.heapify (self.open)
示例#19
0
 def _build_tree(self, a):
     heapq.heapify(a)
     while len(a) > 1:
         left = heapq.heappop(a)
         right = heapq.heappop(a)
         heapq.heappush(a, (left[0] + right[0], left, right))
     return a[0]
示例#20
0
    def test_heapify(self):
        for size in range(30):
            heap = [random.random() for dummy in range(size)]
            heapify(heap)
            self.check_invariant(heap)

        self.assertRaises(TypeError, heapify, None)
示例#21
0
    def add(self, item):
        """ Add *item* to the queue.

            If such an item already exists, its priority will be
            checked versus *item*. If *item*'s priority is better
            (i.e. lower), the priority of the existing item in the
            queue will be updated.

            Returns True if the item was added or updated.
        """
        if not item in self.set:
            self.set[item] = item
            heapq.heappush(self.heap, item)
            return True
        elif item < self.set[item]:
            # No choice but to search linearly in the heap
            #
            for idx, old_item in enumerate(self.heap):
                if old_item == item:
                    del self.heap[idx]
                    self.heap.append(item)
                    heapq.heapify(self.heap)
                    self.set[item] = item
                    return True
        return False
示例#22
0
def main():
    from heapq import heapify, heappush, heappop

    M = open('matrix.txt').read().split()
    M = [map(int, m.split(',')) for m in M]

    H = len(M)
    W = len(M[0])

    scores = [(M[y][0], 0, y) for y in xrange(H)]
    heapify(scores)
    R = [[0]*W for _ in xrange(H)]

    def next(xx, yy):
        if not R[yy][xx]:
            ss = M[yy][xx] + s
            R[yy][xx] = ss
            heappush(scores, (ss, xx, yy))

    while scores:
        s, x, y = heappop(scores)
        if x == W-1:
            #for r in R:
            #    print r
            return s
        if y > 0:
            next(x, y-1)
        if y < H-1:
            next(x, y+1)
        next(x+1, y)
示例#23
0
def shortest_paths(neighs, start):
    """
    Returns a tuple of two dicts (dists, prevs). Dists contains lengths of
    shortest paths from start to all reachable vertices. Prevs contains previous
    vertex of the shortest path, which can be easily used to reconstruct the
    whole path.

    Arguments:
    neighs -- dict of dict such that neighs[v1][v2] = d iff there is an edge
              from v1 to v2 with length d
    start -- the starting vertex
    """
    visited = set()
    to_visit = [(0, start, None)]
    heapq.heapify(to_visit)
    prevs = {} # previous vertex of ideal path
    dists = {}
    while True:
        if not to_visit:
            return dists, prevs
        dist, vertex, prev = heapq.heappop(to_visit)
        if vertex in visited: continue
        for n in neighs[vertex]:
            if n in visited: continue
            heapq.heappush(to_visit, (neighs[vertex][n] + dist, n, vertex))
        prevs[vertex] = prev
        dists[vertex] = dist
        visited.add(vertex)
示例#24
0
def relax(w, u, v):
    global h
    global path

    for node in h:
        d, p, vertex = node
        if vertex == v:
            d_v = d

    for node in path:
        d, p, vertex = node
        if vertex == u:
            d_u = d
        elif vertex == v:
            d_v = d

    if d_v > d_u + w:
        d_v = d_u +w
        p_v = u
        for i in range(len(h)):
            _w, _p, _u = h[i]
            if _u == v:
                h[i] = (d_v, p_v, v)
                break

        heapq.heapify(h)
示例#25
0
    def massReschedule(self, reschedule_set):
        """
        Reschedule all models provided. 
        Equivalent to calling unschedule(model); schedule(model) on every element in the iterable.

        :param reschedule_set: iterable containing all models to reschedule
        """
        #NOTE rather dirty, though a lot faster for huge models
        #assert debug("Mass rescheduling")
        inf = float('inf')
        for model in reschedule_set:
            event = self.id_fetch[model.model_id]
            if event[2]:
                if model.time_next == event[0]:
                    continue
                elif event[0][0] != inf:
                    self.invalids += 1
                event[2] = False
            if model.time_next[0] != inf:
                self.id_fetch[model.model_id] = [model.time_next, 
                                                 model.model_id, 
                                                 True, 
                                                 model]
                heappush(self.heap, self.id_fetch[model.model_id])
        #assert debug("Optimizing heap")
        if self.invalids >= self.max_invalids:
            #assert info("Heap compaction in progress")
            self.heap = [i for i in self.heap if i[2] and (i[0][0] != inf)]
            heapify(self.heap)
            self.invalids = 0
    def nthUglyNumber(self, n):
        """
        Prime factor: 2, 3, 5
        Heap
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1

        n -= 1  # exclude 1

        ugly = [2, 3, 5]
        qs = [Node(i, [i]) for i in ugly]
        h = list(qs)  # shallow copy

        heapq.heapify(h)

        cnt = 0
        ret = 2
        while cnt < n:
            cnt += 1
            popped = heapq.heappop(h)
            ret = popped.q.pop(0)
            for i in xrange(ugly.index(popped.origin), 3):
                qs[i].q.append(ret*ugly[i])

            heapq.heappush(h, popped)

        return ret
示例#27
0
 def __init__(self,source_vertex,vertex_list):
     self.pq = []
     self.source = source_vertex
     for v in vertex_list:
         self.pq.append(v)
     self.source.min_weight = 0
     heapq.heapify(self.pq)
示例#28
0
    def sweep(self):
        """Clean out stale data

            >>> sdc = PersistentSessionDataContainer()
            >>> sdc['1'] = SessionData()
            >>> sdc['2'] = SessionData()

        Wind back the clock on one of the ISessionData's
        so it gets garbage collected

            >>> sdc['2'].lastAccessTime -= sdc.timeout * 2

        Sweep should leave '1' and remove '2'

            >>> sdc.sweep()
            >>> sd1 = sdc['1']
            >>> sd2 = sdc['2']
            Traceback (most recent call last):
                [...]
            KeyError: '2'

        """
        # We only update the lastAccessTime every 'resolution' seconds.
        # To compensate for this, we factor in the resolution when
        # calculating the expiry time to ensure that we never remove
        # data that has been accessed within timeout seconds.
        expire_time = time.time() - self.timeout - self.resolution
        heap = [(v.lastAccessTime, k) for k,v in self.data.items()]
        heapify(heap)
        while heap:
            lastAccessTime, key = heappop(heap)
            if lastAccessTime < expire_time:
                del self.data[key]
            else:
                return
示例#29
0
def first_k_most_relevant(doc_scores):
	"""If there are more than k documents containing terms in a query, return the k documents with the highest scores, tiebroken by least docID first.
	If there are less than k documents, return them, sorted by highest scores, and tiebroken by least docID first. O(n) + O(k lg n)

	:param doc_scores: A dictionary of docID to its corresponding document's score.
	:return: List of k docIDs of string type, which are the most relevant (i.e. have the highest scores)
	"""
	scores = [(-score, docID) for docID, score in doc_scores.iteritems()] # invert the scores so that heappop gives us the smallest score
	heapq.heapify(scores)
	most_relevant_docs = []
	for _ in range(k):
		if not scores:
			break
		most_relevant_docs.append(heapq.heappop(scores))
	if not most_relevant_docs:
		return most_relevant_docs
	# deals with equal-score cases
	kth_score, kth_docID = most_relevant_docs[-1]
	while scores:
		next_score, next_docID = heapq.heappop(scores)
		if next_score == kth_score:
			most_relevant_docs.append((next_score, next_docID))
		else:
			break
	return sort_relevant_docs(most_relevant_docs)
示例#30
0
	def discard(self, item):
		new_heap = []
		for heap_item in self.heap:
			if item != heap_item.item:
				new_heap.append(heap_item)
		self.heap = new_heap
		heapify(self.heap)
# RPC 08 - Rockabye Tobby [TLE]

import heapq

if __name__ == '__main__':
	t = int(input())
	for _ in range(t):
		n, k = [int(x) for x in input().split()]
		medicines = []
		for p in range(n):
			med = input().split()
			medicines.append( (med[0], int(med[1]), p) )
		result = []
		heapq.heapify(result)
		for i in range(k):
			for j in range(n):
				heapq.heappush(result, (medicines[j][1] * (i + 1), medicines[j][2], j) )
		for i in range(k):
			r = heapq.heappop(result)
			print(r[0], medicines[r[2]][0])

def huffman_encode(arr, save_dir='./'):
    """
    Encodes numpy array 'arr' and saves to save_dir
    The names of binary files are prefixed with prefix
    returns the number of bytes for the tree and the data after the compression
    """
    if len(arr) == 0:
        return 0, 0

    # Infer dtype
    dtype = str(arr.dtype)

    # Calculate frequency in arr
    freq_map = defaultdict(int)
    convert_map = {'float32': float, 'int32': int}
    for value in np.nditer(arr):
        value = convert_map[dtype](value)
        freq_map[value] += 1

    # Make heap
    heap = [
        Node(frequency, value, None, None)
        for value, frequency in freq_map.items()
    ]
    heapify(heap)

    # Merge nodes
    while len(heap) > 1:
        node1 = heappop(heap)
        node2 = heappop(heap)
        merged = Node(node1.freq + node2.freq, None, node1, node2)
        heappush(heap, merged)

    # Generate code value mapping
    value2code = dict()

    def generate_code(node, code):
        if node is None:
            return
        if node.value is not None:
            value2code[node.value] = code
            return
        generate_code(node.left, code + '0')
        generate_code(node.right, code + '1')

    root = heappop(heap)
    generate_code(root, '')

    # Path to save location
    directory = Path(save_dir)

    # Dump data
    data_encoding = ''.join(value2code[convert_map[dtype](value)]
                            for value in np.nditer(arr))
    datasize = dump(data_encoding)

    # Dump codebook (huffman tree)
    codebook_encoding = encode_huffman_tree(root, dtype)
    treesize = dump(codebook_encoding)

    return treesize, datasize
示例#33
0
 def _rebuild_heap(self):
     self._heap = [(v, k) for k, v in iteritems(self)]
     heapify(self._heap)
from heapq import heappop, heappush, heapify
"""PYTHON BUILDS MIN HEAPS BY DEFAULT"""
heap = []
nums = [12, 3, -5, 14, 20, -100, 55]

# for num in nums:
#     heappush(heap, num)
#
# while heap:
#     print(heappop(heap))


heapify(nums)
print(nums)
示例#35
0
 def __init__(self) -> None:
     self._heap = []
     heapq.heapify(self._heap)
示例#36
0
文件: iter.py 项目: crnt/kdi
def join(inputs, keyfuncs=None):
    """join(inputs, keyfuncs) --> iterator over tuples of iterators

    General join operator over k inputs yields a k-tuple of iterators,
    such that at least one iterator is over a non-empty sequence.  All
    elements in all iterators have the same join key.

    The join key is derived from each input value using the keyfunc
    parameter.  If not provided, the keyfunc defaults to the identity
    function for each input.  If the keyfunc is indexable, each index
    is associated with the corresponding input; otherwise the same
    keyfunc will be used for all inputs.  Individual keyfuncs that
    aren't callable will default to the identity function.
    
    Example with invariant assertions:

      inputs = (seq1, seq2, ..., seqN)
      keyfuncs = (keyfunc1, keyfunc2, ..., keyfuncN)
      for it_nTuple in join(inputs, keyfuncs):
          assert len(it_nTuple) == N
          itemCount = 0
          commonKey = None
          for it in it_nTuple:
              for i,x in enumerate(it):
                  itemCount += 1
                  if itemCount == 1:
                      commonKey = keyfuncs[i](x)
                  else:
                      assert keyfuncs[i](x) == commonKey
          assert itemCount >= 1

    Special-case join operators:

      0/1 join:

         def singleItemOrNone(it):
             for x in it:
                 break
             else:
                 return None
             for y in it:
                 raise ValueError('Got more than one element')
             else:
                 return x

         for it_nTuple in join((seq1, seq2, ..., seqN)):
             yield map(singleItemOrNone, it_nTuple)
    """

    n = len(inputs)
    iters = map(pushback_iter, inputs)

    if keyfuncs is None:
        keyfuncs = [None] * n
    elif not hasattr(keyfuncs, '__getitem__'):
        keyfuncs = [keyfuncs] * n
    for i, k in enumerate(keyfuncs):
        if not callable(k):
            keyfuncs[i] = lambda x: x

    import heapq
    q = []
    for i, it in enumerate(iters):
        for v in it:
            k = keyfuncs[i](v)
            it.push(v)
            q.append((k, i, it))
            break
    heapq.heapify(q)
    while q:
        k, i, it = q[0]
        it_tuple = tuple([
            iter_equal_key(it2, k, keyfuncs[j]) for j, it2 in enumerate(iters)
        ])
        yield it_tuple
        for x in it_tuple:
            for y in x:
                pass
        while q and q[0][0] == k:
            k, i, it = q[0]
            for v in it:
                nk = keyfuncs[i](v)
                it.push(v)
                heapq.heapreplace(q, (nk, i, it))
                break
            else:
                heapq.heappop(q)
示例#37
0
 format(14, '#010b')
 {}.format(14, '#010b')
#Fill the string with zeros until it is 10 characters long:
txt = "50"
x = txt.zfill(10)
# sort list
orgList
newList = sorted(orgList, key = lambda x: orgList[x])
# or
orgList.sort(orgList, key = lambda x: orgList[x])
# dict to list
l = list(dict.item())
# min heap: from min to max, maintain len 
import heapq
a = [3,2,1]
heapq.heapify(a)
# a become [1,2,3]
if len(heap) < 3:
    heapq.heappush(heap, num) # -num if max heap
else:
    heapq.heappushpop(heap, num)
# !!!!!!!! heappop to get ordered item
#The traditional solution is to store (priority, task) tuples on the heap:

pq = [ ]
heappush(pq, (10, task1))
heappush(pq, (5, task2))
heappush(pq, (15, task3))
priority, task = heappop(pq)

示例#38
0
import heapq
H = [21,1,45,78,3,5]
# Covert to a heap
heapq.heapify(H)
print(H)
# Add element
heapq.heappush(H,8)
print(H)

heapq.heapify(H)
print(H)
示例#39
0
 def _remove(self, item):
     self.queue.remove(item)
     heapq.heapify(self.queue)
import sys
import heapq
sys.stdin = open('1715.txt', 'r')

N = int(input())
cards = []
for _ in range(N):
    cards += [int(input())]

heapq.heapify(cards)

ans = 0
while len(cards) > 1:
    x, y = heapq.heappop(cards), heapq.heappop(cards)

    ans += x + y
    heapq.heappush(cards, x + y)

print(ans)
示例#41
0
            This function increase the value by 1
        """
        self.count += 1

    def __cmp__(self, other):
        """
            This function used by heapify to compare the comments based on their frequency
        """
        return cmp(self.count, other.count)


revheap = {}  # a dictionary of heap

for x in range(12):  # 12 for number of months
    revheap[x] = list()
    heapq.heapify(revheap[x])

alldict = list(
)  # list of dictionary for each month to store comment vs review instance
for x in range(12):
    alldict.append({})


def getData():
    """
        Reading from local postgres db
        database name : review
        user : postgres
        password : root
        table : usercomments(comments  character varying(20),  postdate  date)
    """
示例#42
0
def pythonHeap(arr: list):
    heapq.heapify(arr)
    return [heapq.heappop(arr) for _ in range(len(arr))]
示例#43
0
def get_degree_heap(graph: nx.Graph):
    degrees = [(-d, v) for (v, d) in graph.degree_iter()]
    heapq.heapify(degrees)
    return degrees
示例#44
0
import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data

heapq.heapify(data)
print('start:')
show_tree(data)

for n in [0, 13]:
    smallest = heapq.heapreplace(data, n)
    print('replace %2d with %2d:' % (smallest, n))
    show_tree(data)
示例#45
0
 def resetHeap(self):
     self.heap = self.stack.copy()
     heapq.heapify(self.heap)
示例#46
0
 def __init__(self):
     self.back = []
     heapq.heapify(self.back)
import heapq
import math

m, n = input().split(' ')
# c=0
n = int(n)
arr = list(map(int, input().split(' ')))

arr = [20, 7, 5, 4]
narr = []
# print(arr)

for i in arr:
    narr.append(i * -1)

n = len(arr) - 1

while (n):
    n -= 1
    heapq.heapify(narr)
    ele = heapq.heappop(narr)
    # print(ele)
    heapq.heappush(narr, math.ceil(ele // 2))
    # print(narr)

print(sum(narr) * -1)
from collections import deque
import heapq

import time

array = [6, 2, 8, 1, 3, 9, 4, 5, 10, 7]
heapq.heapify(array)
array = [3, 4, 5, 6, 7, 4, 12, 13, 3]

print(array)


def heapsort(a):
    n = len(a)
    a = [0] + a

    for i in range(int(n / 2), 0, -1):
        heapify(a, i, n)

    for j in range(n - 1, 0, -1):
        a[1], a[j + 1] = a[j + 1], a[1]
        heapify(a, 1, j)


def heapify(a, h, m):
    root = a[h]
    for j in range(2 * h, m - 1, 2):
        if j < m and a[j] < a[j + 1]:
            j += 1
        if root >= a[int(j / 2)]:
            break
print(heap)

# we can do the same operation by heappreplace() method.
small=heapq.heappushpop(heap,(0,"k"))
print(small)
print(heap)
# do that again-
small=heapq.heappushpop(heap,(3,"n"))
print(small)
print(heap)

# the difference between heappushpop() and heappreplace() is:
# in heappushpop() the pop being performed after the push.
# in heappreplace() the pop being performed before the push (in other words, the new
# element cannot be returned as the smallest).

# we can transform a unordered list to a heap using heapify() method.
unordered = [(2,"k"),(0,"g"),(1,"f")]
heapq.heapify(unordered)
print(unordered)

# we can print first n-th largest pair from the heap using nlargest() method.
print(heapq.nlargest(3,heap))
# we can print first n-th smallest pair from the heap using nsmallest() method.
print(heapq.nsmallest(2,heap))

# we can merge two heap and make them one.
merged = list(heapq.merge(heap,unordered)) # NOTE that we have to convert it to list.
print(merged)

 def finalize(self):
     self._final = True
     heapq.heapify(self._l)
 def __init__(self, k: int, nums: List[int]):
     self.nums = nums
     self.k = k
     heapq.heapify(self.nums)
     while len(self.nums) > self.k:
         heapq.heappop(self.nums)
# greedy Huffman's coding algorithm (using weights instead of frequencies of elements)
# printing lengths of the longest and shortest codewords in the resulting Huffman code


import heapq
size = 1000
t = [0]*(size + 1)
with open('huffman.txt', 'r') as doc:
    h = 0
    for line in doc:
        t[h] = int(line)
        h += 1
del t[0]
T = t.copy()
print(T)
heapq.heapify(T)
print(T)
shortest = 0
longest = 0
mini = min(t)
maxi = max(t)
while len(T) > 2:
    a = heapq.heappop(T)
    b = heapq.heappop(T)
    if a == mini or b == mini:
        longest += 1
        mini = a + b
    if a == maxi or b == maxi:
        shortest += 1
        maxi = a + b
    heapq.heappush(T, a + b)
示例#53
0
 def __init__(self, vals=[], key=None):
     self.key = (lambda x: x) if key == None else key
     self.heap = [(self.key(v), v) for v in vals]
     heapify(self.heap)
示例#54
0
def ComputePath(listOpen, target, setClose, counter):
    while (target.gVal > listOpen[0][0]):
        temp = listOpen[0][1]
        heapq.heappop(listOpen)
        setClose.append(temp)

        if (temp.rNode != temp):
            if (temp.rNode.search < counter):
                temp.rNode.gVal = float('Inf')
                temp.rNode.search = counter
            if (temp.rNode.gVal > temp.gVal + 1):
                temp.rNode.gVal = temp.gVal + 1
                temp.rNode.tree = temp
                ifRemove = 0
                for key in listOpen:
                    if key[1] == temp.rNode:
                        listOpen.remove(key)
                        ifRemove = 1
                        break
                f = temp.rNode.gVal + temp.rNode.h_fun(temp.rNode, target)
                if ifRemove == 1:
                    listOpen.append([f, temp.rNode])
                    heapq.heapify(listOpen)
                else:
                    heapq.heappush(listOpen, [f, temp.rNode])

        if (temp.lNode != temp):
            if (temp.lNode.search < counter):
                temp.lNode.gVal = float('Inf')
                temp.lNode.search = counter
            if (temp.lNode.gVal > temp.gVal + 1):
                temp.lNode.gVal = temp.gVal + 1
                temp.lNode.tree = temp
                ifRemove = 0
                for key in listOpen:
                    if key[1] == temp.lNode:
                        listOpen.remove(key)
                        ifRemove = 1
                        break
                f = temp.lNode.gVal + temp.lNode.h_fun(temp.lNode, target)
                if ifRemove == 1:
                    listOpen.append([f, temp.lNode])
                    heapq.heapify(listOpen)
                else:
                    heapq.heappush(listOpen, [f, temp.lNode])

        if (temp.uNode != temp):
            if (temp.uNode.search < counter):
                temp.uNode.gVal = float('Inf')
                temp.uNode.search = counter
            if (temp.uNode.gVal > temp.gVal + 1):
                temp.uNode.gVal = temp.gVal + 1
                temp.uNode.tree = temp
                ifRemove = 0
                for key in listOpen:
                    if key[1] == temp.uNode:
                        listOpen.remove(key)
                        ifRemove = 1
                        break
                f = temp.uNode.gVal + temp.uNode.h_fun(temp.uNode, target)
                if ifRemove == 1:
                    listOpen.append([f, temp.uNode])
                    heapq.heapify(listOpen)
                else:
                    heapq.heappush(listOpen, [f, temp.uNode])

        if (temp.dNode != temp):
            if (temp.dNode.search < counter):
                temp.dNode.gVal = float('Inf')
                temp.dNode.search = counter
            if (temp.dNode.gVal > temp.gVal + 1):
                temp.dNode.gVal = temp.gVal + 1
                temp.dNode.tree = temp
                ifRemove = 0
                for key in listOpen:
                    if key[1] == temp.dNode:
                        listOpen.remove(key)
                        ifRemove = 1
                        break
                f = temp.dNode.gVal + temp.dNode.h_fun(temp.dNode, target)
                if ifRemove == 1:
                    listOpen.append([f, temp.dNode])
                    heapq.heapify(listOpen)
                else:
                    heapq.heappush(listOpen, [f, temp.dNode])
#        print(len(listOpen))
        if len(listOpen) == 0:
            return
示例#55
0
 def __delitem__(self, key):
     """Delete the first occurrence of key."""
     self.heap.remove((self.f(key), key))
     heapq.heapify(self.heap)
示例#56
0
    def flood_fill(self, x, y, final_x, final_y):
        print("In Flood Fill")
        map_img = np.flipud(self.map_array.copy())
        unknown_spaces = np.where(map_img == -1)  # -1 means unknown
        map_img[unknown_spaces] = 100  # turn everything unknown into a wall
        # plt.imshow(map_img, cmap='gray', vmin=-1, vmax=100)
        # plt.show(True)
        # quit()

        nodes = [(0, (x, y))]
        heapify(nodes)

        while nodes:
            # pop the node
            node = heapq.heappop(nodes)
            # print(node)
            # get its values
            cur_p = node[0]
            cur_x, cur_y = node[1]

            # update the map object
            self.cost_map[cur_x][cur_y] = cur_p

            # get neighbors
            open_pixels, near_walls = self.get_neighbors(
                map_img, cur_x, cur_y, 8)
            neighbors = open_pixels + near_walls

            # already skipping occupied spaces
            for neighbor in neighbors:
                n_x = neighbor[0]
                n_y = neighbor[1]
                n = np.array([n_x, n_y])

                # make the path distance the priority
                new_p = (cur_p + np.linalg.norm(np.array([cur_x, cur_y]) - n))

                # print(idx)
                idx = [(a, b) for a, b in near_walls if a == n_x and b == n_y]
                if len(idx) > 0:
                    new_p *= 100

                if (n_x, n_y) == (final_x, final_y):
                    self.cost_map[n_x][n_y] = new_p
                    print("found the goal")
                    return True

                # if self.near_wall(map_img, n_x, n_y):
                #     new_p *= new_p  # square the distance to disuade path's near walls

                # if the block is already seen, possibly update priority
                if self.cost_map[n_x][n_y] != np.inf:
                    # get the p value that matches the node in the heap
                    old_p = [a for a, b in nodes if (n_x, n_y) == b]
                    if len(old_p) > 1:
                        print("Error - quiting")
                        quit()

                    if new_p < old_p:  # if new distance is shorter than before, update it
                        idx = nodes.index((old_p[0], (n_x, n_y)))
                        nodes[idx] = (new_p, (n_x, n_y))
                        heapify(nodes)  # rebalance the heap
                else:
                    self.cost_map[n_x][n_y] = new_p
                    heapq.heappush(nodes, (new_p, (n_x, n_y)))

            # plt.imsave("flood.png", self.cost_map, cmap='gray', vmin=0, vmax=300)
            # plt.show()
        print("could not find goal")
        return False
示例#57
0
文件: util.py 项目: yonnn/eloipool
 def _build_heap(self):
     newheap = list((v[0], k, v[1]) for k, v in self._dict.items())
     heapq.heapify(newheap)
     self._heap = newheap
 def topKFrequent(self, words, k):
     count = collections.Counter(words)
     heap = [(-freq, word) for word, freq in count.items()]
     heapq.heapify(heap)
     return [heapq.heappop(heap)[1] for _ in range(k)]
示例#59
0
 def __init__(self, k: int, nums: List[int]):
     self.pool = nums
     self.k = k
     heapq.heapify(self.pool)
     while len(self.pool) > k:
         heapq.heappop(self.pool)
示例#60
0
 def __init__(self, k, nums):
     self.heap = nums
     heapq.heapify(self.heap)
     self.k = k