实验4: 递归, 树递归, Python 列表
Lab 4: Recursion, Tree Recursion, Python Lists

Due by 11:59pm on Tuesday, September 22.

查看英文原文

初始文件

下载 lab04.zip。 在压缩包中,你可以找到本实验问题的初始文件,以及一份 Ok 自动评分器。

主要内容

如果你需要复习本实验的材料,请参考本节。你可以直接跳到问题部分,遇到困难再回到这里。

Recursion

A recursive function is a function that calls itself in its body, either directly or indirectly. Recursive functions have three important components:

  1. Base case(s), the simplest possible form of the problem you're trying to solve.
  2. Recursive case(s), where the function calls itself with a simpler argument as part of the computation.
  3. Using the recursive calls to solve the full problem.

Let's look at the canonical example, factorial.

Factorial, denoted with the ! operator, is defined as:

n! = n * (n-1) * ... * 1

For example, 5! = 5 * 4 * 3 * 2 * 1 = 120

The recursive implementation for factorial is as follows:

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

We know from its definition that 0! is 1. Since n == 0 is the smallest number we can compute the factorial of, we use it as our base case. The recursive step also follows from the definition of factorial, i.e., n! = n * (n-1)!.

The next few questions in lab will have you writing recursive functions. Here are some general tips:

  • Paradoxically, to write a recursive function, you must assume that the function is fully functional before you finish writing it; this is called the recursive leap of faith.
  • Consider how you can solve the current problem using the solution to a simpler version of the problem. The amount of work done in a recursive function can be deceptively little: remember to take the leap of faith and trust the recursion to solve the slightly smaller problem without worrying about how.
  • Think about what the answer would be in the simplest possible case(s). These will be your base cases - the stopping points for your recursive calls. Make sure to consider the possibility that you're missing base cases (this is a common way recursive solutions fail).
  • It may help to write an iterative version first.

Tree Recursion

A tree recursive function is a recursive function that makes more than one call to itself, resulting in a tree-like series of calls.

A classic example of a tree recursion function is finding the nth Fibonacci number:

def fib(n):
    if n == 0 or n == 1:
        return n
    return fib(n - 1) + fib(n - 2)

Calling fib(6) results in the following call structure (where f is fib):

Fibonacci Tree

Each f(i) node represents a recursive call to fib. Each recursive call makes another two recursive calls. f(0) and f(1) do not make any recursive calls because they are the base cases of the function. Because of these base cases, we are able to terminate the recursion and beginning accumulating the values.

Generally, tree recursion is effective when you want to explore multiple possibilities or choices at a single step. In these types of problems, you make a recursive call for each choice or for a group of choices. Here are some examples:

  • Given a list of paid tasks and a limited amount of time, which tasks should you choose to maximize your pay? This is actually a variation of the Knapsack problem, which focuses on finding some optimal combination of different items.
  • Suppose you are lost in a maze and see several different paths. How do you find your way out? This is an example of path finding, and is tree recursive because at every step, you could have multiple directions to choose from that could lead out of the maze.
  • Your dryer costs $2 per cycle and accepts all types of coins. How many different combinations of coins can you create to run the dryer? This is similar to the partitions problem from the textbook.

Lists

Lists are Python data structures that can store multiple values. Each value can be any type and can even be another list! A list is written as a comma separated list of expressions within square brackets:

>>> list_of_nums = [1, 2, 3, 4]
>>> list_of_bools = [True, True, False, False]
>>> nested_lists = [1, [2, 3], [4, [5]]]

Each element in a list is assigned an index. Lists are zero-indexed, meaning their indices start at 0 and increase in sequential order. To retrieve an element from a list, use list indexing:

>>> lst = [6, 5, 4, 3, 2, 1]
>>> lst[0]
6
>>> lst[3]
3

Often times we need to know how long a list is when we're working with it. To find the length of a list, call the function len on it:

>>> len([])
0
>>> len([2, 4, 6, 8, 10])
5

Tip: Recall that empty lists, [], are false-y values. Therefore, you can use an if statement like the following if you only want to do operations on non-empty lists:

if lst:
    # Do stuff with the elements of list

This is equivalent to:

if len(lst) > 0:
    # Do stuff

You can also create a copy of some portion of the list using list slicing. To slice a list, use this syntax: lst[<start index>:<end index>]. This expression evaluates to a new list containing the elements of lst starting at and including the element at <start index> up to but not including the element at end index.

>>> lst = [True, False, True, True, False]
>>> lst[1:4]
[False, True, True]
>>> lst[:3]  # Start index defaults to 0
[True, False, True]
>>> lst[3:]  # End index defaults to len(lst)
[True, False]
>>> lst[:]  # Creates a copy of the whole list
[True, False, True, True, False]

必答题

列表练习

Q1: 列表索引

使用 Ok 测试你对以下“列表索引”问题的理解:

python3 ok -q list-indexing -u --local

对于以下每个列表,哪个列表索引表达式的结果是 7?例如,如果 x = [7],那么答案就是 x[0]。你可以使用解释器或 Python Tutor 来实验你的答案。如果代码会导致错误,请输入 Error

>>> x = [1, 3, [5, 7], 9]
______
x[2][1]
>>> x = [[3, [5, 7], 9]]
______
x[0][1][1]

Python 会输出什么?如果遇到困难,可以在 Python 解释器中尝试运行!

>>> lst = [3, 2, 7, [84, 83, 82]]
>>> lst[4]
______
Error
>>> lst[3][0]
______
84

递归

Q2: 跳跃相加

编写一个函数 skip_add,它接受一个参数 n,并计算从 0n 之隔一个数相加的和。假设 n 是非负数。

this_file = __file__

def skip_add(n):
    """ Takes a number n and returns n + n-2 + n-4 + n-6 + ... + 0.

    >>> skip_add(5)  # 5 + 3 + 1 + 0
    9
    >>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0
    30
    >>> # Do not use while/for loops!
    >>> from construct_check import check
    >>> # ban iteration
    >>> check(this_file, 'skip_add',
    ...       ['While', 'For'])
    True
    """
    "*** YOUR CODE HERE ***"

使用 Ok 来测试你的代码:

python3 ok -q skip_add --local

Q3: 求和

现在,请编写一个递归实现的 summation 函数,该函数接受一个正整数 n 和一个函数 term。它将 term 应用于从 1n(包括 n)的每个数,并返回结果的总和。

def summation(n, term):

    """Return the sum of the first n terms in the sequence defined by term.
    Implement using recursion!

    >>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
    225
    >>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
    54
    >>> summation(5, lambda x: 2**x) # 2^1 + 2^2 + 2^3 + 2^4 + 2^5
    62
    >>> # Do not use while/for loops!
    >>> from construct_check import check
    >>> # ban iteration
    >>> check(this_file, 'summation',
    ...       ['While', 'For'])
    True
    """
    assert n >= 1
    "*** YOUR CODE HERE ***"

使用 Ok 来测试你的代码:

python3 ok -q summation --local

树递归

Q4: 昆虫路径

考虑一个 M x N 的网格中的昆虫。昆虫从左下角 (0, 0) 出发,希望到达右上角 (M-1, N-1)。昆虫只能向右或向上移动。请编写一个函数 paths,该函数接受网格的长度和宽度,并返回昆虫从起点到目标点可以采取的不同路径的数量。(此问题有一个 封闭形式解,但请尝试使用递归的方法来解决。)

grid

例如,对于 2 x 2 的网格,昆虫总共有 2 种方式从起点移动到目标点。对于 3 x 3 的网格,昆虫有 6 种不同的路径(上图仅展示了其中 3 种)。

def paths(m, n):
    """Return the number of paths from one corner of an
    M by N grid to the opposite corner.

    >>> paths(2, 2)
    2
    >>> paths(5, 7)
    210
    >>> paths(117, 1)
    1
    >>> paths(1, 157)
    1
    """
    "*** YOUR CODE HERE ***"

使用 Ok 来测试你的代码:

python3 ok -q paths --local

Q5: 最大子序列

一个数字的子序列是该数字的一系列(不一定连续的)数字。例如,12345 的子序列包括 123、234、124、245 等。你的任务是获取长度不超过特定值的最大子序列。

def max_subseq(n, t):
    """
    Return the maximum subsequence of length at most t that can be found in the given number n.
    For example, for n = 20125 and t = 3, we have that the subsequences are
        2
        0
        1
        2
        5
        20
        21
        22
        25
        01
        02
        05
        12
        15
        25
        201
        202
        205
        212
        215
        225
        012
        015
        025
        125
    and of these, the maxumum number is 225, so our answer is 225.

    >>> max_subseq(20125, 3)
    225
    >>> max_subseq(20125, 5)
    20125
    >>> max_subseq(20125, 6) # note that 20125 == 020125
    20125
    >>> max_subseq(12345, 3)
    345
    >>> max_subseq(12345, 0) # 0 is of length 0
    0
    >>> max_subseq(12345, 1)
    5
    """
    "*** YOUR CODE HERE ***"

解决这个问题有两个关键点:

  • 你需要区分两种情况:使用个位数和不使用个位数的情况。如果使用了个位数,我们需要减少 t,因为我们已经用掉了一个数字;如果不使用,则保持 t 不变。
  • 在使用个位数的情况下,需要将该数字重新添加到末尾。将一个数字 d 附加到数字 n 的末尾的方法是 10 * n + d

使用 Ok 来测试你的代码:

python3 ok -q max_subseq --local

Submit

Make sure to submit this assignment by running:

python3 ok --submit

选做题

虽然“添加字符”是可选的,但它对于 Cats 项目提供了良好练习,因此强烈推荐完成!

Q6: 添加字符

给定两个单词 w1w2,如果 w1w2 的子序列, 则表示 w1 中的所有字母都按相同的顺序出现在 w2 中(但不一定是连续的)。 换句话说,你可以在 w1 的任意位置添加字母,以得到 w2。 例如,"sing" 是 "absorbing" 的子序列, 而 "cat" 是 "contrast" 的子序列。

实现 add_chars 函数,该函数接收 w1w2 两个参数, 其中 w1w2 的子序列。这意味着 w1 的长度短于 w2。 该函数应返回一个字符串,其中包含需要添加到 w1 以得到 w2 的字符。 你的解决方案必须使用递归

在上述示例中,你需要向 "sing" 添加 "aborb" 以得到 "absorbing", 并需要向 "cat" 添加 "ontrs" 以得到 "contrast"。

你返回的字符串中的字母顺序应该按照从左到右依次添加的顺序。 如果 w2 中有多个字符可以与 w1 中的字符匹配,则使用最左侧的字符。 例如,add_chars("coy", "cacophony") 应返回 "acphon",而不是 "caphon", 因为 "coy" 中的 "c" 对应于 "cacophony" 中的第一个 "c"。

def add_chars(w1, w2):
    """
    Return a string containing the characters you need to add to w1 to get w2.

    You may assume that w1 is a subsequence of w2.

    >>> add_chars("owl", "howl")
    'h'
    >>> add_chars("want", "wanton")
    'on'
    >>> add_chars("rat", "radiate")
    'diae'
    >>> add_chars("a", "prepare")
    'prepre'
    >>> add_chars("resin", "recursion")
    'curo'
    >>> add_chars("fin", "effusion")
    'efuso'
    >>> add_chars("coy", "cacophony")
    'acphon'
    >>> from construct_check import check
    >>> # ban iteration and sets
    >>> check(LAB_SOURCE_FILE, 'add_chars',
    ...       ['For', 'While', 'Set', 'SetComp']) # Must use recursion
    True
    """
    "*** YOUR CODE HERE ***"

使用 Ok 来测试你的代码:

python3 ok -q add_chars --local