Hw06 题解 (UCB CS61A@2021 Fall)


In this question you’ll create a vending machine that only outputs a single product and provides change when needed.

Create a class called VendingMachine that represents a vending machine for some product. A VendingMachineobject returns strings describing its interactions. Remember to match exactly the strings in the doctests – including punctuation and spacing!

Fill in the VendingMachine class, adding attributes and methods as appropriate, such that its behavior matches the following doctests:

Lab10 题解 (UCB CS61A@2021 Fall)

Define a procedure over-or-under which takes in a number num1 and a number num2 and returns the following:

  • -1 if num1 is less than num2
  • 0 if num1 is equal to num2
  • 1 if num1 is greater than num2

Challenge: Implement this in 2 different ways using if and cond!

Lab09 题解 (UCB CS61A@2021-Fall)


A subsequence of a sequence S is a subset of elements from S, in the same order they appear in S. Consider the list [1, 2, 3]. Here are a few of it’s subsequences [], [1, 3], [2], and [1, 2, 3].

Lab08 题解 (UCB CS61A@2021 Fall)

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)


Add a time_to_retire method to the Account class. This method takes in an amount and returns how many years the holder would need to wait in order for the current balance to grow to at least amount, assuming that the bank adds balance times the interest rate to the total balance at the end of every year.

问题描述如下: 每一年你的 balance 都会有利息, 问你哪一年你达到了 amount 可以退休了, 用代码模拟这个过程即可

Hw05 题解 (UCB CS61A@2021 Fall)

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 sequence seq and returns a generator that yields all permutations of seq. For this question, assume that seq will not be empty.