CS61A 2022 fall lab01
Posted 临风而眠
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CS61A 2022 fall lab01相关的知识,希望对你有一定的参考价值。
CS61A 2022 fall lab01
文章目录
Topics
Division, Floor Div, and Modulo
- True Division:
/
(decimal division) - Floor Division:
//
(integer division)
之前在Homework01里面体会了floor division 和 true division的区别
-
Modulo**😗*
%
(remainder) -
这三个如果右边的operand为0的话,都会抛出
ZeroDivsionError
的错误
Functions
If we want to execute a series of statements over and over, we can abstract them away into a function to avoid repeating code.
Call expressions
A call expression applies a function, which may or may not accept arguments. The call expression evaluates to the function’s return value.↳
The syntax of a function call:
add ( 2 , 3 )
| | |
operator operand operand
Every call expression requires a set of parentheses delimiting its comma-separated operands.
- To evaluate a function call:
- Evaluate the operator, and then the operands (from left to right).
- Apply the operator to the operands (the values of the operands).
If an operand is a nested call expression, then these two steps are applied to that inner operand first in order to evaluate the outer operand.
return
and print
-
return
- The return statement will give the result of some computation back to the caller of the function and exit the function.
- When Python executes a return statement, the function terminates immediately. If Python reaches the end of the function body without executing a return statement, it will automatically return None.
-
print
- the
print
function is used to display values in the Terminal. This can lead to some confusion betweenprint
andreturn
because calling a function in the Python interpreter will print out the function’s return value.
- the
-
Notice
def what_prints(): print('Hello World!') return 'Exiting this function.' print('61A is awesome!') >>> what_prints() Hello World! 'Exiting this function.'
Notice also that
print
will display text without the quotes, butreturn
will preserve the quotes.
Control
Boolean operators
-
Python supports three boolean operators:
and
,or
, andnot
-
The order of operation
not
has the highest priorityand
or
has the lowest priority
-
Truthy and Falsey Values: It turns out
and
andor
work on more than just booleans (True
,False
).- Python values such as
0
,None
,''
(the empty string), and[]
(the empty list) are considered false values. - All other values are considered true values.
- Python values such as
Shorting Circuiting(短路效应)
-
True or 1 / 0
这个表达式不会抛出Zero DivisionError
Operator Checks if: Evaluates from left to right up to: Example AND All values are true The first false value False and 1 / 0 evaluates to False OR At least one value is true The first true value True or 1 / 0 evaluates to True Short-circuiting happens when the operator reaches an operand that allows them to make a conclusion about the expression. For example, and will short-circuit as soon as it reaches the first false value because it then knows that not all the values are true.
If and and or do not short-circuit, they just return the last value; another way to remember this is that and and or always return the last thing they evaluate, whether they short circuit or not. Keep in mind that and and or don’t always return booleans when using values other than True and False.
If Statements
Tip: We sometimes see code that looks like this:
if x > 3:
return True
else:
return False
This can be written more concisely as return x > 3
. If your code looks like the code above, see if you can rewrite it more clearly!
While Loops
Error Messages
-
一些常见的error
Error Types Descriptions SyntaxError Contained improper syntax (e.g. missing a colon after an if
statement or forgetting to close parentheses/quotes)IndentationError Contained improper indentation (e.g. inconsistent indentation of a function body) TypeError Attempted operation on incompatible types (e.g. trying to add a function and a number) or called function with the wrong number of arguments ZeroDivisionError Attempted division by zero -
orz,手把手教如何看error👇
Required Questions
What Would Python Display? (WWPD)
终端里面输入
python3 ok -q control -u
Q2: WWPD: Control
-
题目质量真不错
我这里试了好几次才反应过来,这个知识点在topic里面提到了:
Notice also that
print
will display text without the quotes, butreturn
will preserve the quotes. -
还有几个,感觉都是有一些小trick在里面
这个考察的知识点是那个
- Python values such as
0
,None
,''
(the empty string), and[]
(the empty list) are considered false values. - All other values are considered true values.
- Python values such as
-
呜呜呜要是我在UCB就好了,每次到这里的时候都只能眼巴巴
Q3: WWPD: Veritasiness
-
这几个我不太熟
比如那个True and 13 返回的是13,这个原理是
In Python, the
and
operator returns the first operand if it is evaluated asFalse
, otherwise it returns the second operand. Since the first operand,True
, is evaluated asTrue
, the second operand,13
, is returned. So in this case,True and 13
evaluates to13
.还有那个
False or 0
In Python, the
or
operator returns the first operand that is considered “truthy” (i.e. evaluates toTrue
when used in a boolean context). SinceFalse
is considered “falsy” and0
is considered “falsy” as well,False or 0
will return0
.What would Python display? If you get stuck, try it out in the Python interpreter! >>> True and 13 ? True -- Not quite. Try again! -- ? 13 -- OK! -- >>> False or 0 ? 0 -- OK! -- >>> not 10 ? False -- OK! -- >>> not None ? True -- OK! -- ---------------------------------------------------------------------
-
前面topic里面总结的挺好👇
If and and or do not short-circuit, they just return the last value; another way to remember this is that and and or always return the last thing they evaluate, whether they short circuit or not.
Keep in mind that and and or don’t always return booleans when using values other than True and False.
用这个规则来做,真的很爽, 比如略微复杂的下面这组
--------------------------------------------------------------------- Veritasiness > Suite 1 > Case 2 (cases remaining: 2) What would Python display? If you get stuck, try it out in the Python interpreter! >>> True and 1 / 0 and False # If this errors, just type Error. ? Error -- OK! -- >>> True or 1 / 0 or False # If this errors, just type Error. ? True -- OK! -- >>> True and 0 # If this errors, just type Error. ? 0 -- OK! -- >>> False or 1 # If this errors, just type Error. ? 1 -- OK! -- >>> 1 and 3 and 6 and 10 and 15 # If this errors, just type Error. ? 15 -- OK! -- >>> -1 and 1 > 0 # If this errors, just type Error. ? True -- OK! -- >>> 0 or False or 2 or 1 / 0 # If this errors, just type Error. ? 2 -- OK! -- --------------------------------------------------------------------- Veritasiness > Suite 2 > Case 1
-
下面这组也不错
--------------------------------------------------------------------- Veritasiness > Suite 2 > Case 1 (cases remaining: 1) What would Python display? If you get stuck, try it out in the Python interpreter! >>> not 0 ? True -- OK! -- >>> (1 + 1) and 1 # If this errors, just type Error. If this is blank, just type Nothing. ? 1 -- OK! -- >>> 1/0 or True # If this errors, just type Error. If this is blank, just type Nothing. ? Error -- OK! -- >>> (True or False) and False # If this errors, just type Error. If this is blank, just type Nothing. ? False -- OK! -- ---------------------------------------------------------------------
Q4: Debugging Quiz
-
呜呜,教debug!
In the following traceback, what is the most recent function call? Traceback (most recent call last): File "temp.py", line 10, in <module> f("hi") File "temp.py", line 2, in f return g(x + x, x) File "temp.py", line 5, in g return h(x + y * 5) File "temp.py", line 8, in h return x + 0 TypeError: must be str, not int 0) g(x + x, x) 1) h(x + y * 5) 2) f("hi") 选1
-
这个也是知识漏洞
Q: How do you write a doctest asserting that square(2) == 4? Choose the number of the correct choice: 0) def square(x): ''' square(2) 4 ''' return x * x 1) def square(x): ''' input: 2 output: 4 ''' return x * x 2) def square(x): ''' >>> square(2) 4 ''' return x * x 3) def square(x): ''' doctest: (2, 4) ''' return x * x ? 选2
-
知识漏洞+1
Q: When should you use print statements? Choose the number of the correct choice: 0) To investigate the values of variables at certain points in your code 1) For permanant debugging so you can have long term confidence in your code 2) To ensure that certain conditions are true at certain points in your code ? 选0 -- OK! --
-
还问了
ok autograder
相关的其实下面这个没太明白👇
Q: How do you prevent the ok autograder from interpreting print statements as output? Choose the number of the correct choice: 0) You don't need to do anything, ok only looks at returned values, not printed values 1) Print with # at the front of the outputted line 2) Print with 'DEBUG:' at the front of the outputted line ? 2 -- OK! --
soga,其实lab上方有写
Q: What is the best way to open an interactive terminal to investigate a failing test for question sum_digits in assignment lab01? Choose the number of the correct choice: 0) python3 ok -q sum_digits --trace 1) python3 -i lab01.py 2) python3 ok -q sum_digits -i 3) python3 ok -q sum_digits ? 选2,题目里面说了interactive
orz,还有个专门的 ok help 网站…
下面这个猜对的
Q: What is the best way to look at an environment diagram to investigate a failing test for question sum_digits in assignment lab01? Choose the number of the correct choice: 0) python3 ok -q sum_digits 1) python3 ok -q sum_digits --trace 2) python3 ok -q sum_digits -i 3) python3 -i lab01.py ? 1 -- OK! --
-
编程习惯和相关的也有
Q: Which of the following is NOT true? Choose the number of the correct choice: 0) It is generally bad practice to release code with debugging print statements left in 1) It is generally good practice to release code with assertion statements left in 2) Code that returns a wrong answer instead of crashing is generally better as it at least works fine 3) Testing is very important to ensure robust code 4) Debugging is not a substitute for testing ? 2 -- OK! --
这个本地自动测评,如果中途断了,下次也会自动续上,它是通过Py文件里面的一个布尔变量locked来控制的
Code Writing Questions
Q5: Falling Factorial
Let’s write a function falling, which is a “falling” factorial that takes two arguments, n and k, and returns the product of k consecutive numbers, starting from n and working downwards. When k is 0, the function should return 1.
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
"*** YOUR CODE HERE ***"
这个有点像组合问题的基本公式约分后,分母上剩下的东西
-
我一开始的solution
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 0) 1 """ "*** YOUR CODE HERE ***" if k == 0: return 1 else: res = 1 for i in range(k): res *= n n = n - 1 return res
-
copilot的solution,妥妥orz
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 0) 1 """ "*** YOUR CODE HERE ***" if k == 0: return 1 else: return n * falling(n-1, k-1)
这个方法非常妙,k每次减一减到0,刚好需要k次,那么n也就是乘了k次,而且n也是每次减一
-
官方给的solution,使用了多重赋值表达式
total, stop = 1, n-k while n > stop: total, n = total*n, n-1 return total
发现官方solution经常是反过来考虑的哈哈哈,之前那个hw01里面找一个数的最大因数,是反着来的,这里它也是直接找到了stop的条件
Q6: Sum Digits
Write a function that takes in a nonnegative integer and sums its digits. (Using floor division and modulo might be helpful here!)
def sum_digits(y):
"""Sum all the digits of y.
>>> sum_digits(10) # 1 + 0 = 1 1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12
>>> sum_digits(1234567890) 45
>>> a = sum_digits(123) # make sure that you are using return rather than print >>> a 6 """
"*** YOUR CODE HERE ***"
-
一开始脑子里的两个想法
- 逐位取数字,可以用递归或者循环?
- 先转为字符串,通过split()放入一个list,然后把list里面的字符全都转换为int型,然后循环相加
- 我觉得第二种挺好
- 嘶,哦不,split()是按照中间的空格作为分割条件
- 那么通过循环吧?
-
于是我就用了第二种,先调试调试
-
AC咯
def sum_digits(y): """Sum all the digits of y. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 >>> a = sum_digits(123) # make sure that you are using return rather than print >>> a 6 """ "*** YOUR CODE HERE ***" str_y = str(y) strlis = [] for char in str_y: strlis.append(char) numlis = [int(c) for c in strlis] # print(strlis) # print(numlis) sum = 0 for i in numlis: sum += i return sum
但是,这里用到列表属实是麻烦了…
我给copilot写了个prompt,看看它用这种方法会怎么做,我感觉属实是被AI薄纱了😭
# write here,using loop but not recursion # fisrt convert into string , then use for loop to sum # then convert back to int y = str(y) sum = 0 for i in y: sum += int(i) return sum
-
想想递归怎么做呢
if y < 10: return y else: return y % 10 + sum_digits(y // 10)
除了base case的控制表达式,不一定是
n == 1
那种,也可以是y < 10
这种最后是达到base case再反弹
所以每个之间需要变化和连接
变化就是不断接近base case
y // 10
就是每次不断接近base casey % 10 +
就是和递归的前后项的连接之桥 -
用循环loop,不用recursion怎么写呢
sum = 0 while y > 0: sum += y % 10 y = y // 10 return sum
注意python里面的地板除 floor division
-
Extra Practice
These questions are optional and will not affect your score on this assignment. However, they are great practice for future assignments, projects, and exams. Attempting these questions can be valuable in helping cement your knowledge of course concepts.
Q7: WWPD: What If?
Use Ok to test your knowledge with the following “What Would Python Display?” questions:
python3 ok -q if-statements -u✂️
Hint:
return
) does not cause the function to exit.
>>> def ab(c, d):
... if c > 5:
... print(c)
... elif c > 7:
... print(d)
... print('foo')
>>> ab(10, 20)
(line 1)? 10
(line 2)? foo
-- OK! --
这里有个小trick, 这个有点好玩,c如果小于等于5,也不会进入elif那个分支
这些练习真的对夯实基础很有用啊啊啊啊啊!
What would Python display? If you get stuck, try it out in the Python
interpreter!
>>> def bake(cake, make):
... if cake == 0:
... cake = cake + 1
... print(cake)
... if cake == 1:
... printCS61A 2022 fall HW 01: Functions, Control
CS61A Fall 2020 Project 2 Autocorrected Typing Software 我的思路
[2021 spring] CS61A Lab 2: Higher-Order Functions, Lambda Expressions
CS144 Lab Assignments - 手写TCP - LAB3