CS61A Fall 2021 discussion 6——q5-q7

Q5: Merge

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.

def merge(a, b):
    """
    >>> 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]
    """
    prev = float('-inf') # 省去了多写一遍循环内内容的麻烦
    while True:
        next_a, next_b = next(a), next(b)
        while next_a <= prev:
            next_a = next(a)
        while next_b <= prev:
            next_b = next(b)
        if next_a != next_b:
            if next_a < next_b:
                yield next_a
                yield next_b
            else:
                yield next_b
                yield next_a
        else:
            yield next_a
        prev = max(next_a, next_b)
    

Q6: Primes Generator

Write a function primes_gen that takes a single argument n and yields all prime numbers less than or equal to n in decreasing order. Assume n >= 1. You may use the is_prime function included below, which we implemented in Discussion 3.

Optional Challenge: Now rewrite the generator so that it also prints the primes in ascending order.

def is_prime(n):
    """Returns True if n is a prime number and False otherwise.
    >>> is_prime(2)
    True
    >>> is_prime(16)
    False
    >>> is_prime(521)
    True
    """
    def helper(i):
        if i > (n ** 0.5): # Could replace with i == n
            return True
        elif n % i == 0:
            return False
        return helper(i + 1)
    return helper(2)

def primes_gen(n):
    """Generates primes in decreasing order.
    >>> pg = primes_gen(7)
    >>> list(pg)
    [7, 5, 3, 2]
    """
    if n < 2:
        return
    if is_prime(n):
        yield n
    yield from primes_gen(n - 1)

Q7: (Optional) Mystery Reverse Environment Diagram

Fill in the lines below so that the variables in the global frame are bound to the values below. Note that the image does not contain a full environment diagram. You may only use brackets, colons, p and q in your answer.

Hint: If you get stuck, feel free to try out different combinations in PythonTutor!
CS61A Fall 2021 discussion 6——q5-q7_第1张图片

def mystery(p, q):
    p[1].extend(q)
    q.append(p[1:])

p = [2, 3]
q = [4, [p]]
mystery(q, p)

这题是常规的CS61A交换变量名类型以增加思考难度的题,看多了就习惯了。

pythontutor中的结果如下:
CS61A Fall 2021 discussion 6——q5-q7_第2张图片

你可能感兴趣的:(python,补课,python)