Problem 4: Merge (100pts)
Problem
Write a generator function
mergethat takes in two infinite generatorsaandbthat are in increasing order without duplicates and returns a generator that has all the elements of both generators, in increasing order, without duplicates.
编写一个生成器函数 merge,它接受两个无限生成器 a 和 b(它们按递增顺序排列且没有重复项),并返回一个包含这两个生成器所有元素(按递增顺序排列且没有重复项)的生成器。
def merge(a, b):
"""Merge two generators that are in increasing order and without duplicates.
Return a generator that has all elements of both generators in increasing
order and without duplicates.
>>> def sequence(start, step):
... while True:
... yield start
... start += step
>>> a = sequence(2, 3) # 2, 5, 8, 11, 14, ...
>>> b = sequence(3, 2) # 3, 5, 7, 9, 11, 13, 15, ...
>>> result = merge(a, b) # 2, 3, 5, 7, 8, 9, 11, 13, 14, 15
>>> [next(result) for _ in range(10)]
[2, 3, 5, 7, 8, 9, 11, 13, 14, 15]
"""
"*** YOUR CODE HERE ***"
Hints
Hint: You may assume that both
aandbcontains infinitely many elements. As a result, callingnext(a)andnext(b)will never throwStopIterationexception.
-
您可以假设
a和b都包含无限多的元素。因此,调用next(a)和next(b)永远不会抛出StopIteration异常。 -
可以用列表偷鸡(属于是猜测数据大小了(
Solutions
注意 a 和 b 都是无穷序列,所以不需要使用 try。
def merge(a, b):
next_a, next_b = next(a), next(b)
while True:
if next_a < next_b:
yield next_a
next_a = next(a)
elif next_a == next_b:
yield next_a
next_a, next_b = next(a), next(b)
else:
yield next_b
next_b = next(b)