Skip to content

Problem 4: Merge (100pts)

Problem

Write a generator function merge that takes in two infinite generators a and b that are in increasing order without duplicates and returns a generator that has all the elements of both generators, in increasing order, without duplicates.

编写一个生成器函数 merge,它接受两个无限生成器 ab(它们按递增顺序排列且没有重复项),并返回一个包含这两个生成器所有元素(按递增顺序排列且没有重复项)的生成器。

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 a and b contains infinitely many elements. As a result, calling next(a) and next(b) will never throw StopIteration exception.

  • 您可以假设 ab 都包含无限多的元素。因此,调用 next(a)next(b) 永远不会抛出 StopIteration 异常。

  • 可以用列表偷鸡(属于是猜测数据大小了(

Solutions

注意 ab 都是无穷序列,所以不需要使用 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)