本文整理汇总了Python中heapq.merge方法的典型用法代码示例。如果您正苦于以下问题:Python heapq.merge方法的具体用法?Python heapq.merge怎么用?Python heapq.merge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类heapq
的用法示例。
在下文中一共展示了heapq.merge方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _merge_catchup_txns
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def _merge_catchup_txns(existing_txns, new_txns):
"""
Merge any newly received txns during catchup with already received txns
:param existing_txns:
:param new_txns:
:return:
"""
# TODO: Can we replace this with SortedDict and before merging substract existing transactions from new?
idx_to_remove = []
start_seq_no = new_txns[0][0]
end_seq_no = new_txns[-1][0]
for seq_no, _ in existing_txns:
if seq_no < start_seq_no:
continue
if seq_no > end_seq_no:
break
idx_to_remove.append(seq_no - start_seq_no)
for idx in reversed(idx_to_remove):
new_txns.pop(idx)
return list(merge(existing_txns, new_txns, key=lambda v: v[0]))
示例2: __init__
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def __init__(self, width, height, rot=True, *args, **kwargs):
"""
_skyline is the list used to store all the skyline segments, each
one is a list with the format [x, y, width] where x is the x
coordinate of the left most point of the segment, y the y coordinate
of the segment, and width the length of the segment. The initial
segment is allways [0, 0, surface_width]
Arguments:
width (int, float):
height (int, float):
rot (bool): Enable or disable rectangle rotation
"""
self._waste_management = False
self._waste = WasteManager(rot=rot)
super(Skyline, self).__init__(width, height, rot, merge=False, *args, **kwargs)
示例3: _placement_points_generator
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def _placement_points_generator(self, skyline, width):
"""Returns a generator for the x coordinates of all the placement
points on the skyline for a given rectangle.
WARNING: In some cases could be duplicated points, but it is faster
to compute them twice than to remove them.
Arguments:
skyline (list): Skyline HSegment list
width (int, float): Rectangle width
Returns:
generator
"""
skyline_r = skyline[-1].right
skyline_l = skyline[0].left
# Placements using skyline segment left point
ppointsl = (s.left for s in skyline if s.left+width <= skyline_r)
# Placements using skyline segment right point
ppointsr = (s.right-width for s in skyline if s.right-width >= skyline_l)
# Merge positions
return heapq.merge(ppointsl, ppointsr)
示例4: tree_count_topologies
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def tree_count_topologies(tree, sample_sets):
for u in tree.samples():
if not tree.is_leaf(u):
raise ValueError("Internal samples not supported.")
topology_counter = np.full(tree.tree_sequence.num_nodes, None, dtype=object)
for sample_set_index, sample_set in enumerate(sample_sets):
for u in sample_set:
if not tree.is_sample(u):
raise ValueError(f"Node {u} in sample_sets is not a sample.")
topology_counter[u] = TopologyCounter.from_sample(sample_set_index)
for u in tree.nodes(order="postorder"):
children = []
for v in tree.children(u):
if topology_counter[v] is not None:
children.append(topology_counter[v])
if len(children) > 0:
topology_counter[u] = combine_child_topologies(children)
counters = []
for root in tree.roots:
if topology_counter[root] is not None:
counters.append(topology_counter[root])
return TopologyCounter.merge(counters)
示例5: pauli_product
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def pauli_product(*elements: Pauli) -> Pauli:
"""Return the product of elements of the Pauli algebra"""
result_terms = []
for terms in product(*elements):
coeff = reduce(mul, [term[1] for term in terms])
ops = (term[0] for term in terms)
out = []
key = itemgetter(0)
for qubit, qops in groupby(heapq.merge(*ops, key=key), key=key):
res = next(qops)[1] # Operator: X Y Z
for op in qops:
pair = res + op[1]
res, rescoeff = PAULI_PROD[pair]
coeff *= rescoeff
if res != 'I':
out.append((qubit, res))
p = Pauli(((tuple(out), coeff),))
result_terms.append(p)
return pauli_sum(*result_terms)
示例6: _get_others_current_hand
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def _get_others_current_hand(self, player):
player_up = self.players[get_upstream_player_id(player, self.players)]
player_down = self.players[get_downstream_player_id(
player, self.players)]
others_hand = merge(player_up.current_hand, player_down.current_hand, key=functools.cmp_to_key(doudizhu_sort_card))
return cards2str(others_hand)
#if __name__ == '__main__':
# import numpy as np
# game = SimpleDoudizhuGame()
# state, player_id = game.init_game()
# print(state)
# while not game.is_over():
# action = np.random.choice(list(state['actions']))
# print(action)
# state, next_player_id = game.step(action)
# print(state)
示例7: execute
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def execute(self):
counter = 0
for vcf_file_name in self.vcf_file_names:
input_stream = InputStream(vcf_file_name, self.tempdir)
samples = l_bp.parse_vcf(input_stream, self.vcf_lines, self.vcf_headers, include_ref=self.include_ref)
for sample in samples:
self.vcf_headers.append("##SAMPLE=<ID=" + sample + ">\n")
self.has_genotypes = True
counter += 1
if counter > self.batchsize:
self.vcf_lines.sort(key=l_bp.vcf_line_key)
self.write_temp_file()
counter = 0
# no need to write the final batch to file
# FIXME Replace this with a new VCF class with the headers all added
self.write_header()
self.vcf_lines.sort(key=l_bp.vcf_line_key)
iterables = self.temp_files + [self.vcf_lines]
self.output_handle.writelines(merge(*iterables))
self.close_tempfiles()
示例8: _merged_breakpoints
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def _merged_breakpoints(
fn0: PiecewiseConstantFunction[T],
fn1: PiecewiseConstantFunction[T],
) -> Iterable[Tuple[XValue[T], float, float]]:
bp0 = zip_longest(fn0.breakpoints.items(), [], fillvalue=0)
bp1 = zip_longest(fn1.breakpoints.items(), [], fillvalue=1)
yprev0, yprev1 = fn0._initial_value, fn1._initial_value
for (x, y), fnnum in merge(bp0, bp1):
if fnnum == 0:
yield x, y, yprev1
yprev0 = y
elif fnnum == 1:
yield x, yprev0, y
yprev1 = y
示例9: get_prescriptions_for_dates
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def get_prescriptions_for_dates(dates):
"""
Yield all prescribing data for the given dates as tuples of the form:
bnf_code, practice_code, date, items, quantity, actual_cost, net_cost
sorted by bnf_code, practice and date.
"""
dates = sorted(dates)
filenames = [get_prescribing_filename(date) for date in dates]
missing_files = [f for f in filenames if not os.path.exists(f)]
if missing_files:
raise RuntimeError(
"Some required CSV files were missing:\n {}".format(
"\n ".join(missing_files)
)
)
prescribing_streams = [read_gzipped_prescribing_csv(f) for f in filenames]
# We assume that the input files are already sorted by (bnf_code, practice,
# month) so to ensure that the combined stream is sorted we just need to
# merge them correctly, which heapq.merge handles nicely for us
return heapq.merge(*prescribing_streams)
示例10: nthSuperUglyNumber
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def nthSuperUglyNumber(self, n, primes):
uglies = [1]
def gen(prime):
for ugly in uglies:
yield ugly * prime
merged = heapq.merge(*map(gen, primes))
while len(uglies) < n:
ugly = next(merged)
if ugly != uglies[-1]:
uglies.append(ugly)
return uglies[-1]
# [23] https://leetcode.com/problems/merge-k-sorted-lists/
# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
#
# use merge
示例11: mergeKLists
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def mergeKLists(lists):
# create a generator
def gen(node):
while node:
yield node.val, node
node = node.next
dummy = last = ListNode(None)
for _, last.next in heapq.merge(*map(gen, lists), key=lambda x: x[0]):
last = last.next
return dummy.next
# [23] https://leetcode.com/problems/merge-k-sorted-lists/
# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
#
# use push and pop
示例12: collate
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def collate(*iterables, **kwargs):
"""Return a sorted merge of the items from each of several already-sorted
*iterables*.
>>> list(collate('ACDZ', 'AZ', 'JKL'))
['A', 'A', 'C', 'D', 'J', 'K', 'L', 'Z', 'Z']
Works lazily, keeping only the next value from each iterable in memory. Use
:func:`collate` to, for example, perform a n-way mergesort of items that
don't fit in memory.
If a *key* function is specified, the iterables will be sorted according
to its result:
>>> key = lambda s: int(s) # Sort by numeric value, not by string
>>> list(collate(['1', '10'], ['2', '11'], key=key))
['1', '2', '10', '11']
If the *iterables* are sorted in descending order, set *reverse* to
``True``:
>>> list(collate([5, 3, 1], [4, 2, 0], reverse=True))
[5, 4, 3, 2, 1, 0]
If the elements of the passed-in iterables are out of order, you might get
unexpected results.
On Python 3.5+, this function is an alias for :func:`heapq.merge`.
"""
if not kwargs:
return merge(*iterables)
return _collate(*iterables, **kwargs)
# If using Python version 3.5 or greater, heapq.merge() will be faster than
# collate - use that instead.
示例13: collate
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def collate(*iterables, **kwargs):
"""Return a sorted merge of the items from each of several already-sorted
*iterables*.
>>> list(collate('ACDZ', 'AZ', 'JKL'))
['A', 'A', 'C', 'D', 'J', 'K', 'L', 'Z', 'Z']
Works lazily, keeping only the next value from each iterable in memory. Use
:func:`collate` to, for example, perform a n-way mergesort of items that
don't fit in memory.
If a *key* function is specified, the iterables will be sorted according
to its result:
>>> key = lambda s: int(s) # Sort by numeric value, not by string
>>> list(collate(['1', '10'], ['2', '11'], key=key))
['1', '2', '10', '11']
If the *iterables* are sorted in descending order, set *reverse* to
``True``:
>>> list(collate([5, 3, 1], [4, 2, 0], reverse=True))
[5, 4, 3, 2, 1, 0]
If the elements of the passed-in iterables are out of order, you might get
unexpected results.
On Python 2.7, this function delegates to :func:`heapq.merge` if neither
of the keyword arguments are specified. On Python 3.5+, this function
is an alias for :func:`heapq.merge`.
"""
if not kwargs:
return merge(*iterables)
return _collate(*iterables, **kwargs)
# If using Python version 3.5 or greater, heapq.merge() will be faster than
# collate - use that instead.
示例14: merge_referrer
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def merge_referrer(needle_sources):
merged_num = len(needle_sources)
if merged_num == 0:
return None
sorted_needle_source = sorted(needle_sources, key=lambda needle_source: needle_source['Level'])
needle_ids = [n['NeedleID'] for n in needle_sources]
ndl_src = copy.deepcopy(needle_sources[0])
if set(needle_ids) != set([ndl_src['NeedleID']]):
raise NeedleIdNotEqual(needle_ids)
refs = [n['Referrers'] for n in needle_sources]
refs = heapq.merge(*refs)
ndl_src['Referrers'] = []
for ref in refs:
ndl_src.add_referrer(ref)
if len(ndl_src['Referrers']) > 0:
ndl_src['Meta'] = sorted_needle_source[-1]['Meta']
ndl_src['SysMeta'] = sorted_needle_source[-1]['SysMeta']
ndl_src['Level'] = sorted_needle_source[0]['Level']
return ndl_src
else:
return None
示例15: merge_needle_source_iters
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import merge [as 别名]
def merge_needle_source_iters(*needle_source_iters):
ndl_src_iter = heapq.merge(*needle_source_iters)
ndl_src_curr = ndl_src_iter.next()
ndl_src_next = ndl_src_curr
reserve_del = ndl_src_curr.reserve_del
while True:
merged_ndls = [ndl_src_curr]
for ndl_src_next in ndl_src_iter:
if ndl_src_curr.needle_id_equal(ndl_src_next):
merged_ndls.append(ndl_src_next)
else:
break
if reserve_del and len(merged_ndls) == 1:
yield ndl_src_curr
else:
ndl_src = merge_referrer(merged_ndls)
if ndl_src is not None:
yield ndl_src
if ndl_src_next == merged_ndls[-1]:
break
ndl_src_curr = ndl_src_next