Lab10 题解 (UCB CS61A@2021 Fall)
Q2: Over or Under
Define a procedure
over-or-under
which takes in a numbernum1
and a numbernum2
and returns the following:
- -1 if
num1
is less thannum2
- 0 if
num1
is equal tonum2
- 1 if
num1
is greater thannum2
Challenge: Implement this in 2 different ways using
if
andcond
!Lab09 题解 (UCB CS61A@2021-Fall)
Recursion and Tree Recursion
Q1: Subsequences
A subsequence of a sequence
S
is a subset of elements fromS
, in the same order they appear inS
. Consider the list[1, 2, 3]
. Here are a few of it’s subsequences[]
,[1, 3]
,[2]
, and[1, 2, 3]
.Write a function that takes in a list and returns all possible subsequences of that list. The subsequences should be returned as a list of lists, where each nested list is a subsequence of the original input.
Lab08 题解 (UCB CS61A@2021 Fall)
Q2: Convert Link
Write a function
convert_link
that takes in a linked list and returns the sequence as a Python list. You may assume that the input list is shallow; that is none of the elements is another linked list.Try to find both an iterative and recursive solution for this problem!
迭代的算法很简单, 我们只要创建一个
result
list 来存储结果, 遍历链表的同时记住访问过的数即可Lab07 题解 (UCB CS61A@2021 Fall)
Accounts
Q2: Retirement
Add a
time_to_retire
method to theAccount
class. This method takes in anamount
and returns how many years the holder would need to wait in order for the currentbalance
to grow to at leastamount
, assuming that the bank addsbalance
times theinterest
rate to the total balance at the end of every year.问题描述如下: 每一年你的
balance
都会有利息, 问你哪一年你达到了amount
可以退休了, 用代码模拟这个过程即可Hw05 题解 (UCB CS61A@2021 Fall)
Q1: Generate Permutations
Given a sequence of unique elements, a permutation of the sequence is a list containing the elements of the sequence in some arbitrary order. For example,
[2, 1, 3]
,[1, 3, 2]
, and[3, 2, 1]
are some of the permutations of the sequence[1, 2, 3]
.Implement
gen_perms
, a generator function that takes in a sequenceseq
and returns a generator that yields all permutations ofseq
. For this question, assume thatseq
will not be empty.Lab06 题解 (UCB CS61A@2021 Fall)
Mutability
Write a function which takes in a list
lst
, an argumententry
, and another argumentelem
. This function will check through each item inlst
to see if it is equal toentry
. Upon finding an item equal toentry
, the function should modify the list by placingelem
intolst
right after the item. At the end of the function, the modified list should be returned.See the doctests for examples on how this function is utilized.