├── DISC └── disc01.md ├── Homework ├── hw01.md └── hw01 │ ├── .ok_history │ ├── .ok_storage.bak │ ├── .ok_storage.dat │ ├── .ok_storage.dir │ ├── __pycache__ │ └── hw01.cpython-38.pyc │ ├── hw01.ok │ ├── hw01.py │ └── ok ├── Lab ├── lab01.md └── lab01 │ ├── .ok_history │ ├── .ok_storage.bak │ ├── .ok_storage.dat │ ├── .ok_storage.dir │ ├── __pycache__ │ └── lab01.cpython-38.pyc │ ├── lab01.ok │ ├── lab01.py │ ├── ok │ └── tests │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-38.pyc │ ├── control.cpython-38.pyc │ ├── debugging-quiz.cpython-38.pyc │ ├── if-statements.cpython-38.pyc │ └── short-circuit.cpython-38.pyc │ ├── control.py │ ├── debugging-quiz.py │ ├── if-statements.py │ └── short-circuit.py ├── Notes ├── 3 Higher-Order Functions.md └── 4 Environments.md ├── Projects ├── hog.md └── hog │ ├── calc.py │ ├── dice.py │ ├── gui_files │ ├── common_server.py │ ├── favicon.gif │ ├── index.html │ └── static │ │ ├── css │ │ ├── 2.17e5ed98.chunk.css │ │ ├── 2.d9ad5f5c.chunk.css │ │ └── main.dfa42325.chunk.css │ │ └── js │ │ ├── 2.14215b64.chunk.js │ │ ├── 2.14215b64.chunk.js.LICENSE │ │ ├── 2.36722391.chunk.js │ │ ├── 2.36722391.chunk.js.LICENSE │ │ ├── 2.50b6458a.chunk.js │ │ ├── 2.50b6458a.chunk.js.LICENSE.txt │ │ ├── 2.cbd40270.chunk.js │ │ ├── 2.cbd40270.chunk.js.LICENSE │ │ ├── main.00c07ad4.chunk.js │ │ ├── main.25a3d700.chunk.js │ │ ├── main.4d7efde4.chunk.js │ │ ├── main.4f75ff99.chunk.js │ │ ├── main.65d320cb.chunk.js │ │ ├── runtime-main.53f79363.js │ │ └── runtime-main.71e877b4.js │ ├── hog.py │ ├── hog_gui.py │ ├── ok │ ├── proj01.ok │ ├── tests │ ├── 00.py │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04a.py │ ├── 04b.py │ ├── 05.py │ ├── 06.py │ ├── 07.py │ ├── 08.py │ ├── 09.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── __init__.py │ ├── check_strategy.py │ ├── construct_check.py │ └── play_utils.py │ └── ucb.py ├── README.md ├── lab └── lab00 │ ├── .ok_history │ ├── .ok_storage.bak │ ├── .ok_storage.dat │ ├── .ok_storage.dir │ ├── __pycache__ │ └── lab00.cpython-38.pyc │ ├── lab00.ok │ ├── lab00.py │ ├── ok │ └── tests │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-38.pyc │ └── python-basics.cpython-38.pyc │ └── python-basics.py └── notes ├── 1 Functions.md └── 2 Control.md /DISC/disc01.md: -------------------------------------------------------------------------------- 1 | Discussion 1 Control and Environments 2 | 3 | # 1 Control 4 | 5 | 巴拉巴拉 6 | 7 | ## Qusetion 8 | 9 | Alfonso will only wear a jacket outside if it is below 60 degrees or it is raining. 10 | 阿方索只有在低于60度或下雨时才会在外面穿夹克。 11 | 12 | Write a function that takes in the current temperature and a boolean value telling if it is raining and returns True if Alfonso will wear a jacket and False otherwise. 13 | 编写一个函数,该函数接收当前温度和布尔值,指示是否下雨,如果Alfonso将穿上夹克,则返回True,否则返回False。 14 | 15 | First, try solving this problem using an if statement. 16 | 首先,尝试使用 if 语句解决此问题。 17 | 18 | ``` 19 | def wears_jacket_with_if(temp, raining): 20 | """ 21 | >>> wears_jacket_with_if(90, False) 22 | False 23 | >>> wears_jacket_with_if(40, False) 24 | True 25 | >>> wears_jacket_with_if(100, True) 26 | True 27 | """ 28 | 29 | ``` 30 | 31 | ``` 32 | def wears_jacket_with_if(temp, raining): 33 | if (temp < 60 or raining): 34 | return True 35 | else: 36 | return False 37 | ``` 38 | Note that we’ll either return True or False based on a single condition, whose 39 | truthiness value will also be either True or False. Knowing this, try to write this 40 | function using a single line. 41 | 42 | ``` 43 | def wears_jacket_with_if(temp, raining): 44 | return temp>=60 or raining 45 | 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /Homework/hw01.md: -------------------------------------------------------------------------------- 1 | # Homework 1: Variables & Functions, Control 2 | 3 | ## 解析 4 | 5 | ### Q2: A Plus Abs B 6 | 要求填空完成 7 | ``` 8 | from operator import add, sub 9 | 10 | if b < 0: 11 | f = _____ 12 | else: 13 | f = _____ 14 | ``` 15 | 刚开始直接打上了 a-b 和 a+b 16 | 然后发现不对,f是个函数,又注意到 importl 了 add 和 sub ,感情是填写这俩 17 | 18 | 但是不知`sub()`的作用: 19 | ``` 20 | operator.sub(a, b) 21 | operator.__sub__(a, b) 22 | 返回 a - b。 23 | ``` 24 | 25 | 26 | 27 | 顺便一提: 28 | ``` 29 | python3 ok -q a_plus_abs_b --local 30 | ``` 31 | ### Q3: Two of Three 32 | 要求一行返回 三数中较小两数的平方之和 33 | 34 | 35 | ### Q4: Largest Factor 36 | 37 | 返回不等于n的n的最大因子,而且提示了使用`%` 38 | 从 n-1 开始遍历,如果 n % i == 0,则返回 i,否则 i-- 直到 i == 1 39 | 40 | ### Q5: If Function vs Statement 41 | 42 | 首先有个 `if_function` , 是普通的if 43 | 44 | 又整了个 `with_if_statement` 要打印 47 ,但是没 return 45 | 还整了个 `with_if_function` 要打印 42 和 47,但是没 return 46 | 47 | 其中 statement : 48 | ``` 49 | if cond(): 50 | return true_func() 51 | else: 52 | return false_func() 53 | ``` 54 | functions: 55 | ``` 56 | return if_function(cond(), true_func(), false_func()) 57 | 58 | ``` 59 | 60 | 要你写出来 `cond()` ` true_func()` ` false_func()` 61 | 62 | 人是懵的,但是可以抽丝剥茧来分析,从已知的 `if_function(condition, true_result, false_result)`来看: 63 | `condition`本质上是个 bool 类型, 要么 true 要么 false,对应的`cond()`应该是返回二者之一,但是不确定打印不打印 64 | 那么 `true_result` 和 `false_result` 就是单纯的打印语句了,但是也有可能为空 65 | 66 | 那么再从 `with_if_statement` 下手,要打印 47 : 67 | 假设 `cond()` 返回 `true` 则执行了 `true_result` 68 | 假设 `cond()` 返回 `false` 则执行了 `false_result` 69 | 那么有如下可能 70 | 1. cond() 返回 `true`,打印 47 ,`true_result` 为空 71 | 2. cond() 返回 `false`,打印 47 ,`false_result` 为空 72 | 3. cond() 返回 `true` ,`true_result` 打印 47 73 | 4. cond() 返回 `false` ,`false_result` 打印 47 74 | 75 | 这时候再看 `with_if_function` ,还记得在: 76 | Calling User-Defined Functions 里的三部曲 77 | Procedure for calling/applying user-defined functions (version 1): 78 | 1. Add a local frame, forming a new environment 79 | **2. Bind the function's formal parameters to its arguments in that frame** 80 | 3. Execute the body of the function in that new environment 81 | 82 | 注意 `with_if_function` 函数的 formal parameters 83 | ``` def if_function(condition, true_result, false_result) ``` 84 | 执行的时候会把这个三个函数按顺序执行一遍,那么,在 1-4 的条件内,缺失的函数需要执行打印42的功能,而且必须是 42 47 的打印顺序 85 | 86 | ### Q6: Hailstone 87 | 巴拉巴拉... 88 | 1. 初始化一个整数 n 89 | 2. n 是偶数,则 n / 2 90 | 3. n 是奇数,则 n * 3 + 1 91 | 4. n = 1 结束 92 | 93 | 94 | --- 95 | 96 | ## 答案 97 | 98 | ### Q2: A Plus Abs B 99 | 100 | 101 | ``` 102 | if b < 0: 103 | f = sub 104 | else: 105 | f = add 106 | return f(a, b) 107 | ``` 108 | 109 | ### Q3: Two of Three 110 | 111 | ``` 112 | return min(x*x + y*y, x*x + z*z, y*y + z*z) 113 | # return x*x + y*y + z*z - max(x, y, z) * max(x, y, z) 114 | 115 | ``` 116 | 117 | ### Q4: Largest Factor 118 | 119 | ``` 120 | res = n-1 121 | while n%res !=0 : 122 | res -= 1 123 | return res 124 | 125 | ``` 126 | ### Q5: If Function vs Statement 127 | 128 | 129 | 130 | ``` 131 | def cond(): 132 | return False 133 | 134 | def true_func(): 135 | print(42) 136 | 137 | def false_func(): 138 | print(47) 139 | 140 | ``` 141 | 142 | ``` 143 | def cond(): 144 | print(42) 145 | return False 146 | 147 | def true_func(): 148 | print(47) 149 | 150 | def false_func(): 151 | pass 152 | 153 | ``` 154 | 155 | ``` 156 | def cond(): 157 | print(42) 158 | return False 159 | 160 | def true_func(): 161 | pass 162 | 163 | def false_func(): 164 | print(47) 165 | ``` 166 | ### Q6: Hailstone 167 | 168 | ``` 169 | res = 1 170 | print(n) 171 | while(n!=1): 172 | if(n%2==0): 173 | n = n/2 174 | else: 175 | n = n*3+1 176 | res+=1 177 | print(int(n)) 178 | return res 179 | ``` -------------------------------------------------------------------------------- /Homework/hw01/.ok_history: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Homework/hw01/.ok_history -------------------------------------------------------------------------------- /Homework/hw01/.ok_storage.bak: -------------------------------------------------------------------------------- 1 | 'a_plus_abs_b-correct', (0, 70) 2 | 'two_of_three-correct', (512, 70) 3 | 'with_if_function-correct', (1024, 70) 4 | 'hailstone-correct', (1536, 70) 5 | -------------------------------------------------------------------------------- /Homework/hw01/.ok_storage.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Homework/hw01/.ok_storage.dat -------------------------------------------------------------------------------- /Homework/hw01/.ok_storage.dir: -------------------------------------------------------------------------------- 1 | 'a_plus_abs_b-correct', (0, 70) 2 | 'two_of_three-correct', (512, 70) 3 | 'with_if_function-correct', (1024, 70) 4 | 'hailstone-correct', (1536, 70) 5 | -------------------------------------------------------------------------------- /Homework/hw01/__pycache__/hw01.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Homework/hw01/__pycache__/hw01.cpython-38.pyc -------------------------------------------------------------------------------- /Homework/hw01/hw01.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Homework 1", 3 | "endpoint": "cal/cs61a/fa20/hw01", 4 | "src": [ 5 | "hw01.py" 6 | ], 7 | "tests": { 8 | "hw*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "a_plus_abs_b", 13 | "two_of_three", 14 | "largest_factor", 15 | "with_if_function", 16 | "with_if_statement", 17 | "hailstone" 18 | ], 19 | "protocols": [ 20 | "file_contents", 21 | "grading", 22 | "analytics", 23 | "backup" 24 | ] 25 | } -------------------------------------------------------------------------------- /Homework/hw01/hw01.py: -------------------------------------------------------------------------------- 1 | from operator import add, sub 2 | 3 | def a_plus_abs_b(a, b): 4 | """Return a+abs(b), but without calling abs. 5 | 6 | >>> a_plus_abs_b(2, 3) 7 | 5 8 | >>> a_plus_abs_b(2, -3) 9 | 5 10 | >>> # a check that you didn't change the return statement! 11 | >>> import inspect, re 12 | >>> re.findall(r'^\s*(return .*)', inspect.getsource(a_plus_abs_b), re.M) 13 | ['return f(a, b)'] 14 | """ 15 | if b < 0: 16 | f = sub 17 | else: 18 | f = add 19 | return f(a, b) 20 | 21 | 22 | def two_of_three(x, y, z): 23 | """Return a*a + b*b, where a and b are the two smallest members of the 24 | positive numbers x, y, and z. 25 | 26 | >>> two_of_three(1, 2, 3) 27 | 5 28 | >>> two_of_three(5, 3, 1) 29 | 10 30 | >>> two_of_three(10, 2, 8) 31 | 68 32 | >>> two_of_three(5, 5, 5) 33 | 50 34 | >>> # check that your code consists of nothing but an expression (this docstring) 35 | >>> # a return statement 36 | >>> import inspect, ast 37 | >>> [type(x).__name__ for x in ast.parse(inspect.getsource(two_of_three)).body[0].body] 38 | ['Expr', 'Return'] 39 | """ 40 | return min(x*x + y*y, x*x + z*z, y*y + z*z) 41 | # return x*x + y*y + z*z - max(x, y, z) * max(x, y, z) 42 | 43 | 44 | def largest_factor(n): 45 | """Return the largest factor of n that is smaller than n. 46 | 47 | >>> largest_factor(15) # factors are 1, 3, 5 48 | 5 49 | >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40 50 | 40 51 | >>> largest_factor(13) # factor is 1 since 13 is prime 52 | 1 53 | """ 54 | res = n-1 55 | while n%res !=0 : 56 | res -= 1 57 | return res 58 | 59 | 60 | def if_function(condition, true_result, false_result): 61 | """Return true_result if condition is a true value, and 62 | false_result otherwise. 63 | 64 | >>> if_function(True, 2, 3) 65 | 2 66 | >>> if_function(False, 2, 3) 67 | 3 68 | >>> if_function(3==2, 3+2, 3-2) 69 | 1 70 | >>> if_function(3>2, 3+2, 3-2) 71 | 5 72 | """ 73 | if condition: 74 | return true_result 75 | else: 76 | return false_result 77 | 78 | 79 | def with_if_statement(): 80 | """ 81 | >>> result = with_if_statement() 82 | 47 83 | >>> print(result) 84 | None 85 | """ 86 | if cond(): 87 | return true_func() 88 | else: 89 | return false_func() 90 | 91 | def with_if_function(): 92 | """ 93 | >>> result = with_if_function() 94 | 42 95 | 47 96 | >>> print(result) 97 | None 98 | """ 99 | return if_function(cond(), true_func(), false_func()) 100 | 101 | def cond(): 102 | print(42) 103 | return False 104 | 105 | def true_func(): 106 | pass 107 | 108 | def false_func(): 109 | print(47) 110 | 111 | 112 | 113 | def hailstone(n): 114 | """Print the hailstone sequence starting at n and return its 115 | length. 116 | 117 | >>> a = hailstone(10) 118 | 10 119 | 5 120 | 16 121 | 8 122 | 4 123 | 2 124 | 1 125 | >>> a 126 | 7 127 | """ 128 | res = 1 129 | print(n) 130 | while(n!=1): 131 | if(n%2==0): 132 | n = n/2 133 | else: 134 | n = n*3+1 135 | res+=1 136 | print(int(n)) 137 | return res 138 | -------------------------------------------------------------------------------- /Homework/hw01/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Homework/hw01/ok -------------------------------------------------------------------------------- /Lab/lab01.md: -------------------------------------------------------------------------------- 1 | # lab 01 2 | 3 | ## What Would Python Display? (Part 1) 4 | ### Q1: WWPD: Control 5 | 6 | 上来 7 | ``` 8 | python3 ok -q control -u 9 | 10 | ``` 11 | 然后答题就行 12 | 13 | #### xc() 14 | ``` 15 | 16 | >>> xk(10, 10) 17 | ? 23 18 | -- OK! -- 19 | 20 | >>> xk(10, 6) 21 | ? 23 22 | -- OK! -- 23 | 24 | >>> xk(4, 6) 25 | ? 6 26 | -- OK! -- 27 | 28 | >>> xk(0, 0) 29 | ? 25 30 | -- OK! -- 31 | ``` 32 | 33 | #### how_big() 34 | 35 | 这里有个小坑,注意 x>5 的return 36 | 37 | ``` 38 | ? big 39 | -- Not quite. Try again! -- 40 | 41 | ? 'big' 42 | -- OK! -- 43 | 44 | >>> how_big(12) 45 | ? huge 46 | -- OK! -- 47 | 48 | >>> how_big(1) 49 | ? small 50 | -- OK! -- 51 | 52 | >>> how_big(-1) 53 | ? nothin 54 | -- OK! -- 55 | ``` 56 | #### n while 57 | 注意是一行一行打印 58 | 59 | ``` 60 | (line 1)? 2 61 | (line 2)? 1 62 | (line 3)? 0 63 | (line 4)? -1 64 | -- OK! -- 65 | ``` 66 | #### positive while 67 | 68 | 这里需要注意,对 python 来说什么时候是 true 什么是 false 69 | 做这里时候应该只学到 Control ,那么已知的 False 值有 : False, 0, '', None 70 | 71 | 72 | ``` 73 | Infinite Loop 74 | ``` 75 | 76 | #### positive negative 77 | ``` 78 | (line 1)? -12 79 | (line 2)? -9 80 | (line 3)? -6 81 | ``` 82 | 83 | ### Q2: WWPD: Veritasiness Veritasiness 84 | 85 | PS:视频里是让你去阅读材料 86 | 87 | To evaluate the expression ` and `: 88 | 89 | 1. Evaluate the subexpression . 90 | 2. If the result is a false value v, then the expression evaluates to v. 91 | 3. Otherwise, the expression evaluates to the value of the subexpression . 92 | 93 | 对 and : 94 | 1. 先求 left 的值 95 | 2. 如果 left 是 false ,那么就返回 left 96 | 3 否则,返回 right 的值 97 | 98 | To evaluate the expression or : 99 | 100 | 1. Evaluate the subexpression . 101 | 2. If the result is a true value v, then the expression evaluates to v. 102 | 3. Otherwise, the expression evaluates to the value of the subexpression . 103 | 104 | 对 or : 105 | 1. 先求 left 的值 106 | 2. 如果 left 是 true ,那么就返回 left 107 | 3. 否则,返回 right 的值 108 | 109 | To evaluate the expression not : 110 | 111 | Evaluate ; The value is True if the result is a false value, and False otherwise. 112 | 113 | 对 not : 114 | 1. 先求 exp 的值 115 | 2. 如果 exp 是 false ,那么就返回 true 116 | 3. 否则,返回 false 117 | 118 | 119 | 120 | ``` 121 | >>> True and 13 122 | ? 13 123 | -- OK! -- 124 | 125 | # and -> left 是 T -> 返回 13 的值:13 126 | 127 | >>> False or 0 128 | ? 0 129 | -- OK! -- 130 | 131 | # or -> left 是 F -> 返回 0 的值:0 132 | 133 | >>> not 10 134 | ? False 135 | -- OK! -- 136 | 137 | # not -> 10 是 T -> 返回 F 138 | 139 | >>> not None 140 | ? True 141 | -- OK! -- 142 | 143 | # not -> None 是 F -> 返回 T 144 | ``` 145 | 146 | ``` 147 | >>> True and 1 / 0 and False # If this errors, just type Error. 148 | ? Error 149 | -- OK! -- 150 | 151 | # and -> left 是 T -> 返回 1 / 0 的值:Error 152 | 153 | >>> True or 1 / 0 or False # If this errors, just type Error. 154 | ? True 155 | -- OK! -- 156 | 157 | # or -> left 是 T -> 返回 True 的值:True 158 | 159 | >>> True and 0 # If this errors, just type Error. 160 | ? 0 161 | -- OK! -- 162 | 163 | # and -> left 是 T -> 返回 0 的值:0 164 | 165 | >>> False or 1 # If this errors, just type Error. 166 | ? 1 167 | -- OK! -- 168 | 169 | # or -> left 是 F -> 返回 1 的值:1 170 | 171 | >>> 1 and 3 and 6 and 10 and 15 # If this errors, just type Error. 172 | ? 15 173 | -- OK! -- 174 | 175 | # left 均是 T -> 返回 15 的值:15 176 | 177 | >>> -1 and 1 > 0 # If this errors, just type Error. 178 | ? True 179 | -- OK! -- 180 | 181 | # and -> left 是 T -> 返回 1>0 的值:True 182 | 183 | >>> 0 or False or 2 or 1 / 0 # If this errors, just type Error. 184 | ? 2 185 | -- OK! -- 186 | 187 | # or -> left 是 F -> 返回 False or 2 or 1 / 0 的值-> of -> left 是 Flase -> 返回 2 or 1/0 的值 -> of -> left 是 True -> 返回 2 的值:2 188 | 189 | ``` 190 | 191 | ``` 192 | 193 | >>> not 0 194 | ? True 195 | -- OK! -- 196 | 197 | # 0:False -> 返回 T 198 | 199 | >>> (1 + 1) and 1 # If this errors, just type Error. If this is blank, just type Nothing. 200 | ? 1 201 | -- OK! -- 202 | 203 | # and -> left 1+1 = 2 是 T -> 返回 1 的值:1 204 | 205 | >>> 1/0 or True # If this errors, just type Error. If this is blank, just type Nothing. 206 | ? Error 207 | -- OK! -- 208 | 209 | # or -> left 1/0 是 Error-> Error 210 | 211 | >>> (True or False) and False # If this errors, just type Error. If this is blank, just type Nothing. 212 | ? False 213 | -- OK! -- 214 | 215 | # () -> T or F -> or -> left 是 T -> 返回 T 表达式变为 T and F -> letf 是 T -> 返回 F 的值:F 216 | 217 | ``` 218 | 219 | ### Q3 Debugging Quiz! 220 | 221 | 首先要听话阅读 : https://inst.eecs.berkeley.edu/~cs61a/fa20/articles/debugging.html 222 | 223 | ``` 224 | Q: In the following traceback, what is the most recent function call? 225 | Traceback (most recent call last): 226 | File "temp.py", line 10, in 227 | f("hi") 228 | File "temp.py", line 2, in f 229 | return g(x + x, x) 230 | File "temp.py", line 5, in g 231 | return h(x + y * 5) 232 | File "temp.py", line 8, in h 233 | return x + 0 234 | TypeError: must be str, not int 235 | Choose the number of the correct choice: 236 | 0) g(x + x, x) 237 | 1) h(x + y * 5) 238 | 2) f("hi") 239 | ? 1 240 | -- OK! -- 241 | ``` 242 | 第一行表示 f 有错 243 | 第二行表示 f 中 g 有错 244 | 第三行表示 g 中 h 有错 245 | 最近调用的应是 h 246 | 247 | 当然要是好好看了文档或者对报错有一定了解:“with the most recent function call at the bottom. ” 248 | 249 | ``` 250 | Q: In the following traceback, what is the cause of this error? 251 | Traceback (most recent call last): 252 | File "temp.py", line 10, in 253 | f("hi") 254 | File "temp.py", line 2, in f 255 | return g(x + x, x) 256 | File "temp.py", line 5, in g 257 | return h(x + y * 5) 258 | File "temp.py", line 8, in h 259 | return x + 0 260 | TypeError: must be str, not int 261 | Choose the number of the correct choice: 262 | 0) the code looped infinitely 263 | 1) there was a missing return statement 264 | 2) the code attempted to add a string to an integer 265 | ? 2 266 | -- OK! -- 267 | ``` 268 | 都写了 `TypeError: must be str, not int` 269 | 270 | ``` 271 | Q: How do you write a doctest asserting that square(2) == 4? 272 | Choose the number of the correct choice: 273 | 0) def square(x): 274 | ''' 275 | square(2) 276 | 4 277 | ''' 278 | return x * x 279 | 1) def square(x): 280 | ''' 281 | input: 2 282 | output: 4 283 | ''' 284 | return x * x 285 | 2) def square(x): 286 | ''' 287 | >>> square(2) 288 | 4 289 | ''' 290 | return x * x 291 | 3) def square(x): 292 | ''' 293 | doctest: (2, 4) 294 | ''' 295 | return x * x 296 | ? 2 297 | ``` 298 | 让你判断 doctest 怎么写 299 | 300 | ``` 301 | Q: When should you use print statements? 302 | Choose the number of the correct choice: 303 | 0) To investigate the values of variables at certain points in your code 304 | 1) For permanant debugging so you can have long term confidence in your code 305 | 2) To ensure that certain conditions are true at certain points in your code 306 | ? 0 307 | -- OK! -- 308 | ``` 309 | print 嘛,肯定是为了追踪变量 310 | 311 | ``` 312 | Q: How do you prevent the ok autograder from interpreting print statements as output? 313 | Choose the number of the correct choice: 314 | 0) You don't need to do anything, ok only looks at returned values, not printed values 315 | 1) Print with # at the front of the outputted line 316 | 2) Print with 'DEBUG:' at the front of the outputted line 317 | ? 2 318 | -- OK! -- 319 | ``` 320 | 文档: 321 | "Note: prefixing debug statements with the specific string "DEBUG: " allows them to be ignored 322 | by the ok autograder used by cs61a. Since ok generally tests all the output of your code, 323 | it will fail if there are debug statements that aren't explicitly marked as such, 324 | even if the outputs are identical." 325 | 326 | ``` 327 | Q: What is the best way to open an interactive terminal to investigate a failing test for question sum_digits in assignment lab01? 328 | Choose the number of the correct choice: 329 | 0) python3 ok -q sum_digits --trace 330 | 1) python3 -i lab01.py 331 | 2) python3 ok -q sum_digits -i 332 | 3) python3 ok -q sum_digits 333 | ? 2 334 | -- OK! -- 335 | ``` 336 | 文档 : Interactive Debugging 337 | 338 | ``` 339 | Q: What is the best way to look at an environment diagram to investigate a failing test for question sum_digits in assignment lab01? 340 | Choose the number of the correct choice: 341 | 0) python3 ok -q sum_digits 342 | 1) python3 ok -q sum_digits --trace 343 | 2) python3 ok -q sum_digits -i 344 | 3) python3 -i lab01.py 345 | ? 1 346 | -- OK! -- 347 | ``` 348 | PythonTutor Debugging 349 | 350 | ``` 351 | Q: Which of the following is NOT true? 352 | Choose the number of the correct choice: 353 | 0) It is generally bad practice to release code with debugging print statements left in 354 | 1) Debugging is not a substitute for testing 355 | 2) It is generally good practice to release code with assertion statements left in 356 | 3) Code that returns a wrong answer instead of crashing is generally better as it at least works fine 357 | 4) Testing is very important to ensure robust code 358 | ? 3 359 | -- OK! -- 360 | ``` 361 | 362 | ``` 363 | Q: You get a SyntaxError. What is most likely to have happened? 364 | Choose the number of the correct choice: 365 | 0) You typed a variable name incorrectly 366 | 1) You forgot a return statement 367 | 2) Your indentation mixed tabs and spaces 368 | 3) You had an unmatched parenthesis 369 | ? 3 370 | -- OK! -- 371 | ``` 372 | 373 | ``` 374 | Q: You get a IndentationError. What is most likely to have happened? 375 | Choose the number of the correct choice: 376 | 0) You had an unmatched parenthesis 377 | 1) You typed a variable name incorrectly 378 | 2) Your indentation mixed tabs and spaces 379 | 3) You forgot a return statement 380 | ? 2 381 | -- OK! -- 382 | ``` 383 | 384 | ``` 385 | Q: You get a TypeError: ... 'NoneType' object is not ... . What is most likely to have happened? 386 | Choose the number of the correct choice: 387 | 0) You typed a variable name incorrectly 388 | 1) Your indentation mixed tabs and spaces 389 | 2) You had an unmatched parenthesis 390 | 3) You forgot a return statement 391 | ? 3 392 | -- OK! -- 393 | ``` 394 | 395 | ``` 396 | Q: You get a NameError. What is most likely to have happened? 397 | Choose the number of the correct choice: 398 | 0) You had an unmatched parenthesis 399 | 1) You typed a variable name incorrectly 400 | 2) You forgot a return statement 401 | 3) Your indentation mixed tabs and spaces 402 | ? 1 403 | -- OK! -- 404 | ``` 405 | ## Coding Practice 406 | 407 | 答案在最后 408 | 409 | ### Q4: Falling Factorial 410 | 411 | 完成函数的body:目的是返回 从 n 开始逐渐减一的阶乘,共 k 个 412 | 413 | 边界条件是 k == 0 的时候,需要返回 1 414 | 415 | ### Q5: Sum Digits 416 | 417 | 我这取巧了,千万不要学啊2333,不喜欢标答的格式 418 | 419 | ### ANSWER :Q4 420 | ``` 421 | return 1 if k == 0 else n * falling(n - 1, k - 1) 422 | ``` 423 | 424 | ### ANSWER :Q5 425 | ``` 426 | y = str(y) 427 | res = 0 428 | for i in y: 429 | res += int(i) 430 | return res 431 | ``` 432 | 433 | ## Extra Practice 434 | 435 | ### Q6: WWPD: What If? 436 | 437 | ```python3 ok -q if-statements -u --local``` 438 | 439 | ``` 440 | >>> def ab(c, d): 441 | ... if c > 5: 442 | ... print(c) 443 | ... elif c > 7: 444 | ... print(d) 445 | ... print('foo') 446 | >>> ab(10, 20) 447 | (line 1)? 10 448 | (line 2)? foo 449 | -- OK! -- 450 | ``` 451 | ``` 452 | >>> def bake(cake, make): 453 | ... if cake == 0: 454 | ... cake = cake + 1 455 | ... print(cake) 456 | ... if cake == 1: 457 | ... print(make) 458 | ... else: 459 | ... return cake 460 | ... return make 461 | >>> bake(0, 29) 462 | (line 1)? 1 463 | (line 2)? 29 464 | (line 3)? 29 465 | -- OK! -- 466 | ``` 467 | 468 | ``` 469 | >>> bake(1, "mashed potatoes") 470 | (line 1)? mashed potatoes 471 | (line 2)? "mashed potatoes" 472 | -- OK! -- 473 | ``` 474 | 475 | ## More Coding Practice 476 | ### Q7: Double Eights 477 | 478 | 一样的取巧 479 | ``` 480 | return "88" in str(n) 481 | ``` 482 | -------------------------------------------------------------------------------- /Lab/lab01/.ok_history: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/.ok_history -------------------------------------------------------------------------------- /Lab/lab01/.ok_storage.bak: -------------------------------------------------------------------------------- 1 | 'falling-correct', (0, 70) 2 | 'sum_digits-correct', (512, 70) 3 | 'double_eights-correct', (1024, 70) 4 | -------------------------------------------------------------------------------- /Lab/lab01/.ok_storage.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/.ok_storage.dat -------------------------------------------------------------------------------- /Lab/lab01/.ok_storage.dir: -------------------------------------------------------------------------------- 1 | 'falling-correct', (0, 70) 2 | 'sum_digits-correct', (512, 70) 3 | 'double_eights-correct', (1024, 70) 4 | -------------------------------------------------------------------------------- /Lab/lab01/__pycache__/lab01.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/__pycache__/lab01.cpython-38.pyc -------------------------------------------------------------------------------- /Lab/lab01/lab01.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 1", 3 | "endpoint": "cal/cs61a/fa20/lab01", 4 | "src": [ 5 | "lab01.py" 6 | ], 7 | "tests": { 8 | "lab*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "control", 13 | "short-circuit", 14 | "debugging-quiz", 15 | "falling", 16 | "sum_digits" 17 | ], 18 | "protocols": [ 19 | "restore", 20 | "file_contents", 21 | "analytics", 22 | "unlock", 23 | "grading", 24 | "backup" 25 | ] 26 | } -------------------------------------------------------------------------------- /Lab/lab01/lab01.py: -------------------------------------------------------------------------------- 1 | def falling(n, k): 2 | """Compute the falling factorial of n to depth k. 3 | 4 | >>> falling(6, 3) # 6 * 5 * 4 5 | 120 6 | >>> falling(4, 3) # 4 * 3 * 2 7 | 24 8 | >>> falling(4, 1) # 4 9 | 4 10 | >>> falling(4, 0) 11 | 1 12 | """ 13 | return 1 if k == 0 else n * falling(n - 1, k - 1) 14 | 15 | 16 | 17 | def sum_digits(y): 18 | """Sum all the digits of y. 19 | 20 | >>> sum_digits(10) # 1 + 0 = 1 21 | 1 22 | >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 23 | 12 24 | >>> sum_digits(1234567890) 25 | 45 26 | >>> a = sum_digits(123) # make sure that you are using return rather than print 27 | >>> a 28 | 6 29 | """ 30 | y = str(y) 31 | res = 0 32 | for i in y: 33 | res += int(i) 34 | return res 35 | 36 | 37 | 38 | def double_eights(n): 39 | """Return true if n has two eights in a row. 40 | >>> double_eights(8) 41 | False 42 | >>> double_eights(88) 43 | True 44 | >>> double_eights(2882) 45 | True 46 | >>> double_eights(880088) 47 | True 48 | >>> double_eights(12345) 49 | False 50 | >>> double_eights(80808080) 51 | False 52 | """ 53 | return "88" in str(n) 54 | 55 | 56 | -------------------------------------------------------------------------------- /Lab/lab01/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/ok -------------------------------------------------------------------------------- /Lab/lab01/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/tests/__init__.py -------------------------------------------------------------------------------- /Lab/lab01/tests/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/tests/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /Lab/lab01/tests/__pycache__/control.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/tests/__pycache__/control.cpython-38.pyc -------------------------------------------------------------------------------- /Lab/lab01/tests/__pycache__/debugging-quiz.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/tests/__pycache__/debugging-quiz.cpython-38.pyc -------------------------------------------------------------------------------- /Lab/lab01/tests/__pycache__/if-statements.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/tests/__pycache__/if-statements.cpython-38.pyc -------------------------------------------------------------------------------- /Lab/lab01/tests/__pycache__/short-circuit.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biepin7/cs61a_2020fall_notes/378e444fc89e3972dcc8f4e02a692d86f3a8047c/Lab/lab01/tests/__pycache__/short-circuit.cpython-38.pyc -------------------------------------------------------------------------------- /Lab/lab01/tests/control.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Control', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> def xk(c, d): 10 | ... if c == 4: 11 | ... return 6 12 | ... elif d >= 4: 13 | ... return 6 + 7 + c 14 | ... else: 15 | ... return 25 16 | >>> xk(10, 10) 17 | 23 18 | >>> xk(10, 6) 19 | 23 20 | >>> xk(4, 6) 21 | 6 22 | >>> xk(0, 0) 23 | 25 24 | """, 25 | 'hidden': False, 26 | 'locked': False 27 | }, 28 | { 29 | 'code': r""" 30 | >>> def how_big(x): 31 | ... if x > 10: 32 | ... print('huge') 33 | ... elif x > 5: 34 | ... return 'big' 35 | ... elif x > 0: 36 | ... print('small') 37 | ... else: 38 | ... print("nothin") 39 | >>> how_big(7) 40 | 'big' 41 | >>> how_big(12) 42 | huge 43 | >>> how_big(1) 44 | small 45 | >>> how_big(-1) 46 | nothin 47 | """, 48 | 'hidden': False, 49 | 'locked': False 50 | } 51 | ], 52 | 'scored': False, 53 | 'type': 'wwpp' 54 | }, 55 | { 56 | 'cases': [ 57 | { 58 | 'code': r""" 59 | >>> n = 3 60 | >>> while n >= 0: # If this loops forever, just type Infinite Loop 61 | ... n -= 1 62 | ... print(n) 63 | 2 64 | 1 65 | 0 66 | -1 67 | """, 68 | 'hidden': False, 69 | 'locked': False 70 | }, 71 | { 72 | 'code': r""" 73 | >>> positive = 28 74 | >>> while positive: # If this loops forever, just type Infinite Loop 75 | ... print("positive?") 76 | ... positive -= 3 77 | Infinite Loop 78 | """, 79 | 'hidden': False, 80 | 'locked': False 81 | }, 82 | { 83 | 'code': r""" 84 | >>> positive = -9 85 | >>> negative = -12 86 | >>> while negative: # If this loops forever, just type Infinite Loop 87 | ... if positive: 88 | ... print(negative) 89 | ... positive += 3 90 | ... negative += 3 91 | -12 92 | -9 93 | -6 94 | """, 95 | 'hidden': False, 96 | 'locked': False 97 | } 98 | ], 99 | 'scored': False, 100 | 'type': 'wwpp' 101 | } 102 | ] 103 | } 104 | -------------------------------------------------------------------------------- /Lab/lab01/tests/debugging-quiz.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'debugging-quiz', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'answer': 'h(x + y * 5)', 9 | 'choices': [ 10 | 'f("hi")', 11 | 'g(x + x, x)', 12 | 'h(x + y * 5)' 13 | ], 14 | 'hidden': False, 15 | 'locked': False, 16 | 'question': r""" 17 | In the following traceback, what is the most recent function call? 18 | Traceback (most recent call last): 19 | File "temp.py", line 10, in 20 | f("hi") 21 | File "temp.py", line 2, in f 22 | return g(x + x, x) 23 | File "temp.py", line 5, in g 24 | return h(x + y * 5) 25 | File "temp.py", line 8, in h 26 | return x + 0 27 | TypeError: must be str, not int 28 | """ 29 | }, 30 | { 31 | 'answer': 'the code attempted to add a string to an integer', 32 | 'choices': [ 33 | 'the code attempted to add a string to an integer', 34 | 'the code looped infinitely', 35 | 'there was a missing return statement' 36 | ], 37 | 'hidden': False, 38 | 'locked': False, 39 | 'question': r""" 40 | In the following traceback, what is the cause of this error? 41 | Traceback (most recent call last): 42 | File "temp.py", line 10, in 43 | f("hi") 44 | File "temp.py", line 2, in f 45 | return g(x + x, x) 46 | File "temp.py", line 5, in g 47 | return h(x + y * 5) 48 | File "temp.py", line 8, in h 49 | return x + 0 50 | TypeError: must be str, not int 51 | """ 52 | }, 53 | { 54 | 'answer': "def square(x): ''' >>> square(2) 4 ''' return x * x", 55 | 'choices': [ 56 | r""" 57 | def square(x): 58 | ''' 59 | doctest: (2, 4) 60 | ''' 61 | return x * x 62 | """, 63 | r""" 64 | def square(x): 65 | ''' 66 | input: 2 67 | output: 4 68 | ''' 69 | return x * x 70 | """, 71 | r""" 72 | def square(x): 73 | ''' 74 | square(2) 75 | 4 76 | ''' 77 | return x * x 78 | """, 79 | r""" 80 | def square(x): 81 | ''' 82 | >>> square(2) 83 | 4 84 | ''' 85 | return x * x 86 | """ 87 | ], 88 | 'hidden': False, 89 | 'locked': False, 90 | 'question': 'How do you write a doctest asserting that square(2) == 4?' 91 | }, 92 | { 93 | 'answer': 'To investigate the values of variables at certain points in your code', 94 | 'choices': [ 95 | 'For permanant debugging so you can have long term confidence in your code', 96 | 'To ensure that certain conditions are true at certain points in your code', 97 | 'To investigate the values of variables at certain points in your code' 98 | ], 99 | 'hidden': False, 100 | 'locked': False, 101 | 'question': 'When should you use print statements?' 102 | }, 103 | { 104 | 'answer': "Print with 'DEBUG:' at the front of the outputted line", 105 | 'choices': [ 106 | "You don't need to do anything, ok only looks at returned values, not printed values", 107 | "Print with 'DEBUG:' at the front of the outputted line", 108 | 'Print with # at the front of the outputted line' 109 | ], 110 | 'hidden': False, 111 | 'locked': False, 112 | 'question': 'How do you prevent the ok autograder from interpreting print statements as output?' 113 | }, 114 | { 115 | 'answer': 'python3 ok -q sum_digits -i', 116 | 'choices': [ 117 | 'python3 ok -q sum_digits -i', 118 | 'python3 ok -q sum_digits --trace', 119 | 'python3 ok -q sum_digits', 120 | 'python3 -i lab01.py' 121 | ], 122 | 'hidden': False, 123 | 'locked': False, 124 | 'question': 'What is the best way to open an interactive terminal to investigate a failing test for question sum_digits in assignment lab01?' 125 | }, 126 | { 127 | 'answer': 'python3 ok -q sum_digits --trace', 128 | 'choices': [ 129 | 'python3 ok -q sum_digits -i', 130 | 'python3 ok -q sum_digits --trace', 131 | 'python3 ok -q sum_digits', 132 | 'python3 -i lab01.py' 133 | ], 134 | 'hidden': False, 135 | 'locked': False, 136 | 'question': 'What is the best way to look at an environment diagram to investigate a failing test for question sum_digits in assignment lab01?' 137 | }, 138 | { 139 | 'answer': 'Code that returns a wrong answer instead of crashing is generally better as it at least works fine', 140 | 'choices': [ 141 | 'Code that returns a wrong answer instead of crashing is generally better as it at least works fine', 142 | 'Testing is very important to ensure robust code', 143 | 'Debugging is not a substitute for testing', 144 | 'It is generally bad practice to release code with debugging print statements left in', 145 | 'It is generally good practice to release code with assertion statements left in' 146 | ], 147 | 'hidden': False, 148 | 'locked': False, 149 | 'question': 'Which of the following is NOT true?' 150 | }, 151 | { 152 | 'answer': 'You had an unmatched parenthesis', 153 | 'choices': [ 154 | 'You had an unmatched parenthesis', 155 | 'Your indentation mixed tabs and spaces', 156 | 'You forgot a return statement', 157 | 'You typed a variable name incorrectly' 158 | ], 159 | 'hidden': False, 160 | 'locked': False, 161 | 'question': 'You get a SyntaxError. What is most likely to have happened?' 162 | }, 163 | { 164 | 'answer': 'Your indentation mixed tabs and spaces', 165 | 'choices': [ 166 | 'You had an unmatched parenthesis', 167 | 'Your indentation mixed tabs and spaces', 168 | 'You forgot a return statement', 169 | 'You typed a variable name incorrectly' 170 | ], 171 | 'hidden': False, 172 | 'locked': False, 173 | 'question': 'You get a IndentationError. What is most likely to have happened?' 174 | }, 175 | { 176 | 'answer': 'You forgot a return statement', 177 | 'choices': [ 178 | 'You had an unmatched parenthesis', 179 | 'Your indentation mixed tabs and spaces', 180 | 'You forgot a return statement', 181 | 'You typed a variable name incorrectly' 182 | ], 183 | 'hidden': False, 184 | 'locked': False, 185 | 'question': "You get a TypeError: ... 'NoneType' object is not ... . What is most likely to have happened?" 186 | }, 187 | { 188 | 'answer': 'You typed a variable name incorrectly', 189 | 'choices': [ 190 | 'You had an unmatched parenthesis', 191 | 'Your indentation mixed tabs and spaces', 192 | 'You forgot a return statement', 193 | 'You typed a variable name incorrectly' 194 | ], 195 | 'hidden': False, 196 | 'locked': False, 197 | 'question': 'You get a NameError. What is most likely to have happened?' 198 | } 199 | ], 200 | 'scored': False, 201 | 'type': 'concept' 202 | } 203 | ] 204 | } 205 | -------------------------------------------------------------------------------- /Lab/lab01/tests/if-statements.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'What If?', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> def ab(c, d): 10 | ... if c > 5: 11 | ... print(c) 12 | ... elif c > 7: 13 | ... print(d) 14 | ... print('foo') 15 | >>> ab(10, 20) 16 | 10 17 | foo 18 | """, 19 | 'hidden': False, 20 | 'locked': False 21 | }, 22 | { 23 | 'code': r""" 24 | >>> def bake(cake, make): 25 | ... if cake == 0: 26 | ... cake = cake + 1 27 | ... print(cake) 28 | ... if cake == 1: 29 | ... print(make) 30 | ... else: 31 | ... return cake 32 | ... return make 33 | >>> bake(0, 29) 34 | 1 35 | 29 36 | 29 37 | >>> bake(1, "mashed potatoes") 38 | mashed potatoes 39 | 'mashed potatoes' 40 | """, 41 | 'hidden': False, 42 | 'locked': False 43 | } 44 | ], 45 | 'scored': False, 46 | 'type': 'wwpp' 47 | } 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /Lab/lab01/tests/short-circuit.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Veritasiness', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> True and 13 10 | 13 11 | >>> False or 0 12 | 0 13 | >>> not 10 14 | False 15 | >>> not None 16 | True 17 | """, 18 | 'hidden': False, 19 | 'locked': False 20 | }, 21 | { 22 | 'code': r""" 23 | >>> True and 1 / 0 and False # If this errors, just type Error. 24 | Error 25 | >>> True or 1 / 0 or False # If this errors, just type Error. 26 | True 27 | >>> True and 0 # If this errors, just type Error. 28 | 0 29 | >>> False or 1 # If this errors, just type Error. 30 | 1 31 | >>> 1 and 3 and 6 and 10 and 15 # If this errors, just type Error. 32 | 15 33 | >>> -1 and 1 > 0 # If this errors, just type Error. 34 | True 35 | >>> 0 or False or 2 or 1 / 0 # If this errors, just type Error. 36 | 2 37 | """, 38 | 'hidden': False, 39 | 'locked': False 40 | } 41 | ], 42 | 'scored': False, 43 | 'type': 'wwpp' 44 | }, 45 | { 46 | 'cases': [ 47 | { 48 | 'code': r""" 49 | >>> not 0 50 | True 51 | >>> (1 + 1) and 1 # If this errors, just type Error. If this is blank, just type Nothing. 52 | 1 53 | >>> 1/0 or True # If this errors, just type Error. If this is blank, just type Nothing. 54 | Error 55 | >>> (True or False) and False # If this errors, just type Error. If this is blank, just type Nothing. 56 | False 57 | """, 58 | 'hidden': False, 59 | 'locked': False 60 | } 61 | ], 62 | 'scored': False, 63 | 'type': 'wwpp' 64 | } 65 | ] 66 | } 67 | -------------------------------------------------------------------------------- /Notes/3 Higher-Order Functions.md: -------------------------------------------------------------------------------- 1 | # 3 Higher-Order Functions 2 | 3 | ## Iteration Example 迭代示例 4 | ### The Fibonacci Sequence 5 | 整了个 Fibonacci 的代码 6 | 7 | ## Designing Functions 8 | ### Characteristics of Functions 9 | A function's domain is the set of all inputs it might 10 | possibly take as arguments. 11 | A function's range is the set of output values it might 12 | possibly return. 13 | A pure function's behavior is the relationship it 14 | creates between input and output. 15 | 16 | "三句非常严谨的定义" 17 | 18 | ### A Guide to Designing Function 19 | 20 | - Give each function exactly one job, but make it apply to many related situations 21 | - Don’t repeat yourself (DRY): Implement a process just once, but execute it many times 22 | - Define functions generally 23 | 24 | ## Generalization 25 | ### Generalizing Patterns with Arguments 26 | 27 | PS:到这里我开始后悔了,notion上做代码的对比可能会更好一点 28 | 29 | 首先我们写三个求面积的函数 30 | ``` 31 | def area_square(r): 32 | """Return the area of a square with side length R.""" 33 | return r * r 34 | 35 | def area_circle(r): 36 | """Return the area of a circle with radius R.""" 37 | return r * r * pi 38 | 39 | def area_hexagon(r): 40 | """Return the area of a regular hexagon with side length R.""" 41 | return r * r * 3 * sqrt(3) / 2 42 | ``` 43 | 这时候如果输入的 r 为负数,也会进行计算,为了防止这样的问题,使用 `assert`: 44 | ``` 45 | def area(r, shape_constant): 46 | """Return the area of a shape from length measurement R.""" 47 | assert r > 0, 'A length must be positive' 48 | return r * r * shape_constant 49 | ``` 50 | 51 | 当然,repeat 三次不够优雅: 52 | 53 | ``` 54 | def area(r, shape_constant): 55 | """Return the area of a shape from length measurement R.""" 56 | assert r > 0, 'A length must be positive' 57 | return r * r * shape_constant 58 | 59 | def area_square(r): 60 | return area(r, 1) 61 | 62 | def area_circle(r): 63 | return area(r, pi) 64 | 65 | def area_hexagon(r): 66 | return area(r, 3 * sqrt(3) / 2) 67 | 68 | ``` 69 | 70 | 71 | 72 | ## Higher-Order Functions 73 | 74 | ### Generalizing Over Computational Processes 对计算过程的泛化 75 | 76 | 77 | ``` 78 | def sum_naturals(n): 79 | """Sum the first N natural numbers. 80 | 81 | >>> sum_naturals(5) 82 | 15 83 | """ 84 | total, k = 0, 1 85 | while k <= n: 86 | total, k = total + k, k + 1 87 | return total 88 | 89 | def sum_cubes(n): 90 | """Sum the first N cubes of natural numbers. 91 | 92 | >>> sum_cubes(5) 93 | 225 94 | """ 95 | total, k = 0, 1 96 | while k <= n: 97 | total, k = total + pow(k, 3), k + 1 98 | return total 99 | ``` 100 | 101 | 优化之后是: 102 | 103 | ``` 104 | def identity(k): 105 | return k 106 | 107 | def cube(k): 108 | return pow(k, 3) 109 | 110 | def summation(n, term): 111 | """Sum the first N terms of a sequence. 112 | 113 | >>> summation(5, cube) 114 | 225 115 | """ 116 | total, k = 0, 1 117 | while k <= n: 118 | total, k = total + term(k), k + 1 119 | return total 120 | ``` 121 | 122 | ## Functions as Return Values 123 | 124 | ``` 125 | def make_adder(n): 126 | """Return a function that takes one argument K and returns K + N. 127 | 128 | >>> add_three = make_adder(3) 129 | >>> add_three(4) 130 | 7 131 | """ 132 | def adder(k): 133 | return k + n 134 | return adder 135 | 136 | make_adder(2000)(20) 137 | ``` 138 | 139 | ### Locally Defined Functions && Call Expressions as Operator Expressions 140 | 141 | Functions defined within other function bodies are bound to names in a local frame 142 | 143 | ![](https://raw.githubusercontent.com/biepin7/CloudForImg/master/20220329144031.png) 144 | 145 | ![](https://raw.githubusercontent.com/biepin7/CloudForImg/master/20220329144219.png) 146 | 147 | 注意这里的调用,如果只是单纯调用 `make_adder(2000)` 可以看到return的是一个函数 148 | 149 | ### The Purpose if Higher-Order Functions 150 | 151 | 吐槽这一页最重要的PPT居然没有? 152 | 153 | Functions are first-class : Functions can be manipulate as values in our programming language. 154 | 155 | > 这里我要插句题外话,之前从来不知道这个概念,偶尔刷知乎的时候会看到 函数是一等公民 的说法,每次都感慨文化人说出来的词都不一样,也没细想什么是一等公民,如今可算是明白了 156 | 157 | 158 | 159 | Higher-Order functions (定义): 160 | 161 | A function that either: 162 | 163 | - Takes another function as an argument 164 | - Returns a function as its result 165 | 166 | All other functions are considered first-order functions. 167 | 168 | 169 | 170 | Higher-Order functions(功能): 171 | 172 | - Express general methods of computation 173 | - Remove repetition from programs 174 | - Separate concerns among functions 175 | 176 | 177 | 178 | The common structure among functions may be a computational process, not just a number. 179 | 180 | 函数之间的共同结构可能是一个计算过程,而不仅仅是一个数字。 181 | 182 | ## Lambda expressions 183 | 184 | > 听了一辈子的Lambda ,第一次学什么是 Lambda expressions 185 | 186 | A **lambda expression** is a simple function definition that evaluates to a function. 187 | 188 | The syntax: 189 | 190 | ``` 191 | lambda : 192 | ``` 193 | 194 | A function that takes in `parameters` and returns the result of `expression`. 195 | 196 | 举个例子: 197 | 198 | A lambda version of the `square` function: 199 | 200 | ``` 201 | square = lambda x: x * x 202 | ``` 203 | 204 | ``` 205 | >>> x = 10 206 | >>> square = x*x 207 | >>> square 208 | 100 209 | >>> square = lambda x: x*x 210 | >>> square 211 | at 0x000001F53834D430> 212 | >>> square(4) 213 | 16 214 | >>> (lambda x:x*x)(3) 215 | 9 216 | ``` 217 | 218 | A function that takes in parameter `x` and returns the result of `x * x`. 219 | 220 | A lambda expression does **not** contain return statements or any statements at all. 注意:不包含 return 语句 221 | 222 | ![](https://raw.githubusercontent.com/biepin7/CloudForImg/master/20220329151014.png) 223 | 224 | 注意红框部分,lambda 用来定义简单函数 225 | 226 | ``` 227 | def cube(k): 228 | return k ** 3 229 | 230 | summation(5, cube) 231 | 232 | 233 | summation(5, lambda k: k ** 3) 234 | ``` 235 | 236 | 237 | 238 | ### Lambda Expressions Versus Def Statements def和lambda的区别 239 | 240 | 相同: 241 | 242 | - Both create a function with the same domain, range, and behavior. 243 | - Both bind that function to the name square. 244 | 245 | 不同 246 | 247 | - Only the `def` statement gives the function an **intrinsic name**(固有名称), which shows up in environment diagrams but doesn't affect execution (unless the function is printed). 248 | - ![](https://raw.githubusercontent.com/biepin7/CloudForImg/master/20220329151914.png) 249 | 250 | 可以这么说 lambda 只有赋值结束后才有了名字 251 | 252 | def 没有赋值之前就有了名字 253 | 254 | ## Return 255 | 256 | ### Return Statements 257 | 258 | A return statement completes the evaluation of a call expression and provides its value: 259 | 260 | - f(x) for user-defined function f: switch to a new environment; execute f's body 261 | - return statement within f: switch back to the previous environment; f(x) now has a value 262 | 263 | Only one return statement is ever executed while executing the body of a function 264 | 265 | u1s1 ,略有些废话 266 | 267 | ## Control 268 | 269 | ### If Statements and Call Expressions 270 | 271 | 执行操作什么的就不讲了,在课程里提到一个问题说,为什么不创建一个 `if(a,b,c)`函数来替代 if 语句呢值得想一下 272 | 273 | ``` 274 | lambda x: x if x > 0 else 0 275 | ``` 276 | 277 | A conditional expression has the form 278 | 279 | ``` 280 | if else 281 | ``` 282 | 283 | Evaluation rule: 284 | 1. Evaluate the` ` expression. 285 | 2. If it's a true value, the value of the whole expression is the value of the ``. 286 | 3. Otherwise, the value of the whole expression is the value of the . 287 | 288 | 289 | 290 | -------------------------------------------------------------------------------- /Notes/4 Environments.md: -------------------------------------------------------------------------------- 1 | # 4 Environment 环境 2 | 3 | ## 4.1 Multiple environments 4 | 5 | ### 4.1.1 Environments for Higher-Order Functions 6 | 7 | **Functions are first-class :** Functions are values in our programming language 8 | 9 | **Higher-order function:** A function that takes a function as an argument value or 10 | A function that returns a function as a return value 11 | 12 | > 再次强调 first-class 和 higher-order function 的定义 13 | 14 | ``` 15 | def apply_twice(f,x): 16 | return f(f(x)) 17 | 18 | def square(x): 19 | return x*x 20 | 21 | 22 | >>> square(10) 23 | 100 24 | >>> apply_twice(square,3) 25 | 81 26 | >>> apply_twice(square,10) 27 | 10000 28 | ``` 29 | 30 | > 这里不得不说 2022sp 的 Slides 是设计更为合理的,回忆Life cycle of a function (): 31 | 32 | ![](https://raw.githubusercontent.com/biepin7/CloudForImg/master/20220331095008.png) 33 | 34 | 后面是代码的解析,可以手推就算学会 35 | 36 | > Names have no meanings without environments 37 | 38 | 那么定义一个以下的执行应该等于多少呢 39 | 40 | ``` 41 | def repeat(f,x): 42 | while f(x) != x: 43 | x = f(x) 44 | return x 45 | 46 | def g(y): 47 | return (y+5)//3 48 | 49 | print(repeat(g,5)) 50 | ``` 51 | 52 | ## 4.2 Environments for Nested Definitions 53 | 54 | 本节讲 Nested Definitions 的环境,首先是例子: 55 | 56 | ``` 57 | def make_adder(n): 58 | def adder(x): 59 | return x + n 60 | return adder 61 | 62 | add_three = make_adder(3) 63 | print(add_three) 64 | 65 | print(add_three(4)) 66 | 67 | .adder at 0x0000018757D3D3A0> 68 | 7 69 | ``` 70 | 71 | 这里有一句话:”**So what a return statment does is it brings infomation from a local frame back into the fame that was the current farme when we call this functions in the first place.**" 72 | 73 | - Every user-defined **function** has a parent frame(often global) 74 | - The parent of a **function** is the **frame in which it was defined** 75 | - Every local **frame** has a parent frame 76 | - The parent of a **frame** is the **parent of the called function** 77 | - An environment is a **sequence of frames**. 78 | 79 | ![](https://raw.githubusercontent.com/biepin7/CloudForImg/master/20220331102247.png) 80 | 81 | ### 4.2.1 How to Draw an Environment Diagram 82 | 83 | #### When a function is defined: 84 | 85 | 1. Create a function value: 86 | `func () [parent=