├── LICENSE ├── README.md ├── Snipaste_2022-01-11_16-08-26.png ├── challending_questions ├── challenging_questions.py └── tree.py ├── homework ├── hw01 │ ├── __pycache__ │ │ └── hw01.cpython-39.pyc │ ├── hw01.ok │ ├── hw01.py │ └── ok ├── hw02 │ ├── __pycache__ │ │ ├── construct_check.cpython-39.pyc │ │ └── hw02.cpython-39.pyc │ ├── construct_check.py │ ├── hw02.ok │ ├── hw02.py │ └── ok ├── hw03 │ ├── construct_check.py │ ├── hw03.ok │ ├── hw03.py │ ├── ok │ └── tests │ │ ├── check_par.py │ │ ├── div_interval.py │ │ ├── interval.py │ │ ├── mul_interval.py │ │ ├── polynomial.py │ │ ├── quadratic.py │ │ └── sub_interval.py ├── hw04 │ ├── construct_check.py │ ├── hw04.ok │ ├── hw04.py │ └── ok ├── hw05 │ ├── construct_check.py │ ├── hw05.ok │ ├── hw05.py │ └── ok ├── hw06 │ ├── hw06.ok │ ├── hw06.scm │ └── ok ├── hw07 │ ├── hw07.ok │ ├── hw07.scm │ └── ok ├── hw08 │ ├── hw08.ok │ ├── hw08.scm │ └── ok └── hw09 │ ├── hw09.ok │ ├── hw09.sql │ ├── ok │ └── sqlite_shell.py ├── lab ├── lab00 │ ├── lab00.ok │ ├── lab00.py │ ├── ok │ └── tests │ │ └── python-basics.py ├── lab01 │ ├── lab01.ok │ ├── lab01.py │ ├── ok │ └── tests │ │ ├── control.py │ │ ├── debugging-quiz.py │ │ ├── if-statements.py │ │ └── short-circuit.py ├── lab02 │ ├── lab02.ok │ ├── lab02.py │ ├── ok │ └── tests │ │ ├── hof-wwpd.py │ │ └── lambda.py ├── lab04 │ ├── construct_check.py │ ├── lab04.ok │ ├── lab04.py │ ├── ok │ └── tests │ │ └── list-indexing.py ├── lab05 │ ├── construct_check.py │ ├── lab05.ok │ ├── lab05.py │ └── ok ├── lab06 │ ├── construct_check.py │ ├── lab06.ok │ ├── lab06.py │ ├── ok │ └── tests │ │ └── list-mutation.py ├── lab07 │ ├── car.py │ ├── cardgame.py │ ├── cards.py │ ├── classes.py │ ├── lab07.ok │ ├── lab07.py │ ├── ok │ └── tests │ │ └── wwpd-car.py ├── lab08 │ ├── lab08.ok │ ├── lab08.py │ ├── ok │ └── tests │ │ └── link.py ├── lab09 │ ├── lab09.ok │ ├── lab09.py │ └── ok ├── lab10 │ ├── lab10.ok │ ├── lab10.scm │ └── ok ├── lab11 │ ├── buffer.py │ ├── expr.py │ ├── lab11.ok │ ├── ok │ ├── reader.py │ ├── repl.py │ ├── scheme │ └── utils.py ├── lab12 │ ├── data.sql │ ├── lab12.ok │ ├── lab12.sql │ ├── ok │ ├── sqlite_shell.py │ └── tests │ │ ├── bluedog.py │ │ ├── matchmaker.py │ │ ├── sevens.py │ │ └── smallest-int.py ├── lab13 │ ├── data.sql │ ├── lab13.ok │ ├── lab13.sql │ ├── ok │ └── sqlite_shell.py └── lab14 │ ├── lab14.ok │ ├── lab14.py │ ├── lab14.scm │ └── ok ├── projects ├── ants │ ├── ants.py │ ├── ants_gui.py │ ├── ants_plans.py │ ├── ants_strategies.py │ ├── ants_text.py │ ├── assets │ │ ├── animate.css │ │ ├── app.css │ │ ├── app.js │ │ ├── colony-drawing.png │ │ ├── enchant.js │ │ ├── insects │ │ │ ├── ant_bodyguard.gif │ │ │ ├── ant_fire.gif │ │ │ ├── ant_harvester.gif │ │ │ ├── ant_hungry.gif │ │ │ ├── ant_laser.gif │ │ │ ├── ant_longthrower.gif │ │ │ ├── ant_ninja.gif │ │ │ ├── ant_queen.gif │ │ │ ├── ant_scary.gif │ │ │ ├── ant_scuba.gif │ │ │ ├── ant_shortthrower.gif │ │ │ ├── ant_slow.gif │ │ │ ├── ant_tank.gif │ │ │ ├── ant_thrower.gif │ │ │ ├── ant_wall.gif │ │ │ ├── bee.gif │ │ │ └── remove.png │ │ ├── logo.png │ │ ├── main-background.png │ │ ├── new-ants-gui.png │ │ ├── splash.png │ │ ├── submitted.png │ │ ├── sweetalert.css │ │ ├── sweetalert.min.js │ │ ├── swirl_pattern.png │ │ └── tiles │ │ │ ├── ground │ │ │ ├── 1.png │ │ │ ├── 2.png │ │ │ ├── 3.png │ │ │ └── water.png │ │ │ └── sky │ │ │ ├── 1.png │ │ │ ├── 2.png │ │ │ └── 3.png │ ├── graphics.py │ ├── gui.html │ ├── gui.py │ ├── img │ │ ├── ant_bodyguard.gif │ │ ├── ant_fire.gif │ │ ├── ant_harvester.gif │ │ ├── ant_hungry.gif │ │ ├── ant_laser.gif │ │ ├── ant_longthrower.gif │ │ ├── ant_ninja.gif │ │ ├── ant_queen.gif │ │ ├── ant_scary.gif │ │ ├── ant_scuba.gif │ │ ├── ant_shortthrower.gif │ │ ├── ant_slow.gif │ │ ├── ant_stun.gif │ │ ├── ant_tank.gif │ │ ├── ant_thrower.gif │ │ ├── ant_wall.gif │ │ ├── ants_vs_bees.png │ │ ├── bee.gif │ │ ├── boss.gif │ │ ├── gui_explanation.png │ │ ├── hornet.gif │ │ ├── new_ants_gui.png │ │ ├── ninjabee.gif │ │ ├── remover.gif │ │ ├── tunnel.gif │ │ └── wasp.gif │ ├── ok │ ├── proj03.ok │ ├── state.py │ ├── tests │ │ ├── 00.py │ │ ├── 01.py │ │ ├── 02.py │ │ ├── 03.py │ │ ├── 04.py │ │ ├── 05.py │ │ ├── 06.py │ │ ├── 07.py │ │ ├── 08.py │ │ ├── 09.py │ │ ├── EC.py │ │ ├── optional1.py │ │ ├── optional2.py │ │ ├── optional3.py │ │ ├── optional4.py │ │ └── optional5.py │ ├── ucb.py │ └── utils.py ├── cats │ ├── cats.py │ ├── data │ │ ├── common_words.txt │ │ ├── sample_paragraphs.txt │ │ └── words.txt │ ├── gui.py │ ├── gui_files │ │ ├── FreeMono.ttf │ │ ├── __pycache__ │ │ │ ├── common_server.cpython-39.pyc │ │ │ ├── db.cpython-39.pyc │ │ │ ├── leaderboard_integrity.cpython-39.pyc │ │ │ └── multiplayer.cpython-39.pyc │ │ ├── common_server.py │ │ ├── db.py │ │ ├── favicons │ │ │ ├── crying.ico │ │ │ ├── grinning.ico │ │ │ ├── heart-eyes.ico │ │ │ ├── kissing.png │ │ │ ├── pouting.ico │ │ │ ├── smiling.ico │ │ │ ├── tears-of-joy.ico │ │ │ ├── weary.ico │ │ │ └── wry.ico │ │ ├── index.html │ │ ├── leaderboard_integrity.py │ │ ├── multiplayer.py │ │ ├── precache-manifest.10080bcf5f16dc96f6d8a14870c1bcfe.js │ │ ├── precache-manifest.544d7034191ecf52fa7c157490579669.js │ │ └── static │ │ │ ├── css │ │ │ ├── 2.df9ef6f4.chunk.css │ │ │ └── main.a9291ed5.chunk.css │ │ │ └── js │ │ │ ├── 2.5cb2d1bf.chunk.js │ │ │ ├── main.2b5aa836.chunk.js │ │ │ ├── main.c5c6e95b.chunk.js │ │ │ └── runtime~main.a8a9905a.js │ ├── images │ │ ├── cats_typing.gif │ │ ├── cats_typing_still.gif │ │ ├── fib_tree.png │ │ ├── key_distance_diff_tree.jpeg │ │ └── keyboard.png │ ├── ok │ ├── proj02.ok │ └── tests │ │ ├── 01.py │ │ ├── 02.py │ │ ├── 03.py │ │ ├── 04.py │ │ ├── 05.py │ │ ├── 06.py │ │ ├── 07.py │ │ ├── 08.py │ │ ├── 09.py │ │ ├── 10.py │ │ ├── abstraction_check.py │ │ └── construct_check.py ├── hog │ ├── calc.py │ ├── dice.py │ ├── gui_files │ │ ├── __pycache__ │ │ │ └── common_server.cpython-39.pyc │ │ ├── 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 │ │ ├── check_strategy.py │ │ ├── construct_check.py │ │ └── play_utils.py └── scheme │ ├── __pycache__ │ ├── scheme.cpython-39.pyc │ └── scheme_reader.cpython-39.pyc │ ├── questions.scm │ ├── scheme.py │ ├── scheme_reader.py │ └── tests.scm ├── study guide 1.pdf └── study guide 2.pdf /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 311zzb 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cs61a_fall2020 2 | My solutions to the labs, homework, and projects auditing the CS61a. https://inst.eecs.berkeley.edu/~cs61a/fa20/ 3 | -------------------------------------------------------------------------------- /Snipaste_2022-01-11_16-08-26.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/Snipaste_2022-01-11_16-08-26.png -------------------------------------------------------------------------------- /challending_questions/challenging_questions.py: -------------------------------------------------------------------------------- 1 | def find_paths(t, entry): # CS61a fa20 Disc08 2 | """ 3 | >>> from tree import * 4 | >>> tree_ex = Tree(2, [Tree(7, [Tree(3), Tree(6, [Tree(5), Tree(11)])]), Tree(1, [Tree(5)])]) 5 | >>> find_paths(tree_ex, 5) 6 | [[2, 7, 6, 5], [2, 1, 5]] 7 | >>> find_paths(tree_ex, 12) 8 | [] 9 | """ 10 | # t = Tree(6, [Tree(5), Tree(5)]), entry = 5 11 | paths = [] 12 | if t.label == entry: # if 6 == 5 13 | paths.append([entry]) 14 | for b in t.branches: # b = Tree(5), b = Tree(5) 15 | if find_paths(b, entry): 16 | # paths += [[6] + [5]], paths += [[6] + [5]] 17 | paths += [[t.label] + item for item in find_paths(b, entry)] 18 | return paths # paths = [[6, 5], [6, 5]] 19 | 20 | 21 | def close(n, smallest=10, d=10): # CS61a su20 mt practice q3 22 | """ A sequence is near increasing if each element but the last two is smaller 23 | than all elements following its subsequent element. That is, element i must 24 | be smaller than elements i + 2, i + 3, i + 4. 25 | Implement close, which takes a non-negative integer n and returns the largest 26 | near incresing sequence of digits within n as an integer. The arguments smallest 27 | and d are part of the implementation; you must determine their purpose. The 28 | only values you may use are integers and booleans (no lists, strings, etc.). 29 | Return the longest sequence of near-increasing digits in n. 30 | 31 | >>> close(123) 32 | 123 33 | >>> close(153) 34 | 153 35 | >>> close(1523) 36 | 153 37 | >>> close(15123) 38 | 1123 39 | >>> close(11111111) 40 | 11 41 | >>> close(985357) 42 | 557 43 | >>> close(14735476) 44 | 143576 45 | >>> close(812348567) 46 | 1234567 47 | >>> close(45671) 48 | 4567 49 | """ 50 | # Plan: 51 | # 1) Forget about n % 10 and just find close(n // 10) 52 | # OR 53 | # 2) Use n % 10 and make sure everything before it forms a 54 | # "near-increasing" sequence 55 | # Return whichever is longer(i.e. bigger) among (1) and (2). 56 | if n == 0: 57 | return 0 58 | no = close(n // 10, smallest, d) 59 | if smallest > n % 10: 60 | yes = close(n // 10, min(smallest, d), n % 10) * 10 + n % 10 61 | return max(yes, no) 62 | return no 63 | 64 | 65 | def num_trees(n): # CS61a fa20 lab09 Q4 66 | """How many full binary trees have exactly n leaves? E.g., 67 | 68 | 1 2 3 3 ... 69 | * * * * 70 | / \ / \ / \ 71 | * * * * * * 72 | / \ / \ 73 | * * * * 74 | 75 | >>> num_trees(1) 76 | 1 77 | >>> num_trees(2) 78 | 1 79 | >>> num_trees(3) 80 | 2 81 | >>> num_trees(8) 82 | 429 83 | """ 84 | # Number of leaves in the left branch + number of leaved in the right branch = n 85 | # num_trees_on_left * num_trees_on_right for num_leaved_on_left in range(1, n) 86 | if n == 1: 87 | return 1 88 | return sum([num_trees(i) * num_trees(n-i) for i in range(1,n)]) 89 | 90 | 91 | def num_splits(s, d): # CS61a fa20 lab14 Q4 92 | """Return the number of ways in which s can be partitioned into two 93 | sublists that have sums within d of each other. 94 | 95 | >>> num_splits([1, 5, 4], 0) # splits to [1, 4] and [5] 96 | 1 97 | >>> num_splits([6, 1, 3], 1) # no split possible 98 | 0 99 | >>> num_splits([-2, 1, 3], 2) # [-2, 3], [1] and [-2, 1, 3], [] 100 | 2 101 | >>> num_splits([1, 4, 6, 8, 2, 9, 5], 3) 102 | 12 103 | """ 104 | def helper(s, n): 105 | # S is a list, N is the running difference 106 | if len(s) == 0: 107 | return 1 if abs(n) <= d else 0 108 | else: 109 | # Use s[0] Drop s[0] 110 | return helper(s[1:], n + s[0]) + helper(s[1:], n - s[0]) 111 | return helper(s, 0) // 2 112 | -------------------------------------------------------------------------------- /challending_questions/tree.py: -------------------------------------------------------------------------------- 1 | class Tree: 2 | """ 3 | >>> t = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) 4 | >>> t.label 5 | 3 6 | >>> t.branches[0].label 7 | 2 8 | >>> t.branches[1].is_leaf() 9 | True 10 | """ 11 | def __init__(self, label, branches=[]): 12 | for b in branches: 13 | assert isinstance(b, Tree) 14 | self.label = label 15 | self.branches = list(branches) 16 | 17 | def is_leaf(self): 18 | return not self.branches 19 | 20 | def map(self, fn): 21 | """ 22 | Apply a function `fn` to each node in the tree and mutate the tree. 23 | 24 | >>> t1 = Tree(1) 25 | >>> t1.map(lambda x: x + 2) 26 | >>> t1.map(lambda x : x * 4) 27 | >>> t1.label 28 | 12 29 | >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) 30 | >>> t2.map(lambda x: x * x) 31 | >>> t2 32 | Tree(9, [Tree(4, [Tree(25)]), Tree(16)]) 33 | """ 34 | self.label = fn(self.label) 35 | for b in self.branches: 36 | b.map(fn) 37 | 38 | def __contains__(self, e): 39 | """ 40 | Determine whether an element exists in the tree. 41 | 42 | >>> t1 = Tree(1) 43 | >>> 1 in t1 44 | True 45 | >>> 8 in t1 46 | False 47 | >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) 48 | >>> 6 in t2 49 | False 50 | >>> 5 in t2 51 | True 52 | """ 53 | if self.label == e: 54 | return True 55 | for b in self.branches: 56 | if e in b: 57 | return True 58 | return False 59 | 60 | def __repr__(self): 61 | if self.branches: 62 | branch_str = ', ' + repr(self.branches) 63 | else: 64 | branch_str = '' 65 | return 'Tree({0}{1})'.format(self.label, branch_str) 66 | 67 | def __str__(self): 68 | def print_tree(t, indent=0): 69 | tree_str = ' ' * indent + str(t.label) + "\n" 70 | for b in t.branches: 71 | tree_str += print_tree(b, indent + 1) 72 | return tree_str 73 | return print_tree(self).rstrip() 74 | -------------------------------------------------------------------------------- /homework/hw01/__pycache__/hw01.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw01/__pycache__/hw01.cpython-39.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 x*x + y*y + z*z - max(x,y,z)*max(x,y,z) 41 | 42 | 43 | def largest_factor(n): 44 | """Return the largest factor of n that is smaller than n. 45 | 46 | >>> largest_factor(15) # factors are 1, 3, 5 47 | 5 48 | >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40 49 | 40 50 | >>> largest_factor(13) # factor is 1 since 13 is prime 51 | 1 52 | """ 53 | k = n - 1 54 | while n % k != 0: 55 | k -= 1 56 | return k 57 | 58 | 59 | def if_function(condition, true_result, false_result): 60 | """Return true_result if condition is a true value, and 61 | false_result otherwise. 62 | 63 | >>> if_function(True, 2, 3) 64 | 2 65 | >>> if_function(False, 2, 3) 66 | 3 67 | >>> if_function(3==2, 3+2, 3-2) 68 | 1 69 | >>> if_function(3>2, 3+2, 3-2) 70 | 5 71 | """ 72 | if condition: 73 | return true_result 74 | else: 75 | return false_result 76 | 77 | 78 | def with_if_statement(): 79 | """ 80 | >>> result = with_if_statement() 81 | 47 82 | >>> print(result) 83 | None 84 | """ 85 | if cond(): 86 | return true_func() 87 | else: 88 | return false_func() 89 | 90 | def with_if_function(): 91 | """ 92 | >>> result = with_if_function() 93 | 42 94 | 47 95 | >>> print(result) 96 | None 97 | """ 98 | return if_function(cond(), true_func(), false_func()) 99 | 100 | def cond(): 101 | return False 102 | 103 | def true_func(): 104 | print(42) 105 | 106 | def false_func(): 107 | print(47) 108 | 109 | 110 | def hailstone(n): 111 | """Print the hailstone sequence starting at n and return its 112 | length. 113 | 114 | >>> a = hailstone(10) 115 | 10 116 | 5 117 | 16 118 | 8 119 | 4 120 | 2 121 | 1 122 | >>> a 123 | 7 124 | """ 125 | assert n > 0 and isinstance(n, int), "The input to hailstone() must be a positive integer." 126 | steps = 1 127 | while n != 1: 128 | print(n) 129 | steps += 1 130 | if n % 2 == 0: 131 | n = n // 2 132 | else: 133 | n = n * 3 + 1 134 | print(1) 135 | return steps 136 | -------------------------------------------------------------------------------- /homework/hw01/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw01/ok -------------------------------------------------------------------------------- /homework/hw02/__pycache__/construct_check.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw02/__pycache__/construct_check.cpython-39.pyc -------------------------------------------------------------------------------- /homework/hw02/__pycache__/hw02.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw02/__pycache__/hw02.cpython-39.pyc -------------------------------------------------------------------------------- /homework/hw02/hw02.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Homework 2", 3 | "endpoint": "cal/cs61a/fa20/hw02", 4 | "src": [ 5 | "hw02.py" 6 | ], 7 | "tests": { 8 | "hw*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "num_eights", 13 | "pingpong", 14 | "missing_digits", 15 | "count_coins" 16 | ], 17 | "protocols": [ 18 | "restore", 19 | "file_contents", 20 | "grading", 21 | "analytics", 22 | "backup" 23 | ] 24 | } -------------------------------------------------------------------------------- /homework/hw02/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw02/ok -------------------------------------------------------------------------------- /homework/hw03/hw03.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Homework 3", 3 | "endpoint": "cal/cs61a/fa20/hw03", 4 | "src": [ 5 | "hw03.py" 6 | ], 7 | "tests": { 8 | "hw*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "total_weight", 13 | "balanced", 14 | "totals_tree", 15 | "replace_leaf", 16 | "preorder", 17 | "has_path" 18 | ], 19 | "protocols": [ 20 | "restore", 21 | "file_contents", 22 | "unlock", 23 | "grading", 24 | "analytics", 25 | "backup" 26 | ] 27 | } -------------------------------------------------------------------------------- /homework/hw03/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw03/ok -------------------------------------------------------------------------------- /homework/hw03/tests/check_par.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'check_par', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> r1, r2 = check_par() 10 | >>> x = par1(r1, r2) 11 | >>> y = par2(r1, r2) 12 | >>> lower_bound(x) != lower_bound(y) or upper_bound(x) != upper_bound(y) 13 | True 14 | """, 15 | 'hidden': False, 16 | 'locked': False 17 | } 18 | ], 19 | 'scored': True, 20 | 'setup': r""" 21 | >>> import hw03 22 | >>> from hw03 import * 23 | """, 24 | 'teardown': '', 25 | 'type': 'doctest' 26 | }, 27 | { 28 | 'cases': [ 29 | { 30 | 'code': r""" 31 | >>> # Testing for abstraction violations 32 | >>> # Your code should not check for which implementation is used 33 | >>> r1, r2 = check_par() 34 | >>> x = par1(r1, r2) 35 | >>> y = par2(r1, r2) 36 | >>> lower_bound(x) != lower_bound(y) or upper_bound(x) != upper_bound(y) 37 | True 38 | """, 39 | 'hidden': False, 40 | 'locked': False 41 | } 42 | ], 43 | 'scored': True, 44 | 'setup': r""" 45 | >>> import hw03 46 | >>> old_abstraction = hw03.interval, hw03.lower_bound, hw03.upper_bound 47 | >>> hw03.interval = lambda a, b: lambda x: a if x == 0 else b 48 | >>> hw03.lower_bound = lambda s: s(0) 49 | >>> hw03.upper_bound = lambda s: s(1) 50 | >>> from hw03 import * 51 | """, 52 | 'teardown': r""" 53 | >>> hw03.interval, hw03.lower_bound, hw03.upper_bound = old_abstraction 54 | """, 55 | 'type': 'doctest' 56 | } 57 | ] 58 | } 59 | -------------------------------------------------------------------------------- /homework/hw03/tests/div_interval.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'div_interval', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> # Type AssertionError if you think an AssertionError is raised 10 | >>> str_interval(div_interval(interval(-1, 2), interval(4, 8))) 11 | '-0.25 to 0.5' 12 | >>> str_interval(div_interval(interval(4, 8), interval(-1, 2))) 13 | AssertionError 14 | """, 15 | 'hidden': False, 16 | 'locked': False 17 | } 18 | ], 19 | 'scored': True, 20 | 'setup': r""" 21 | >>> import hw03 22 | >>> from hw03 import * 23 | """, 24 | 'teardown': '', 25 | 'type': 'doctest' 26 | }, 27 | { 28 | 'cases': [ 29 | { 30 | 'code': r""" 31 | >>> # Testing for abstraction violations 32 | >>> # Your code should not check for which implementation is used 33 | >>> str_interval(div_interval(interval(-1, 2), interval(4, 8))) 34 | '-0.25 to 0.5' 35 | >>> str_interval(div_interval(interval(4, 8), interval(-1, 2))) 36 | AssertionError 37 | """, 38 | 'hidden': False, 39 | 'locked': False 40 | } 41 | ], 42 | 'scored': True, 43 | 'setup': r""" 44 | >>> import hw03 45 | >>> old_abstraction = hw03.interval, hw03.lower_bound, hw03.upper_bound 46 | >>> hw03.interval = lambda a, b: lambda x: a if x == 0 else b 47 | >>> hw03.lower_bound = lambda s: s(0) 48 | >>> hw03.upper_bound = lambda s: s(1) 49 | >>> from hw03 import * 50 | """, 51 | 'teardown': r""" 52 | >>> hw03.interval, hw03.lower_bound, hw03.upper_bound = old_abstraction 53 | """, 54 | 'type': 'doctest' 55 | } 56 | ] 57 | } 58 | -------------------------------------------------------------------------------- /homework/hw03/tests/interval.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'interval', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> str_interval(interval(-1, 2)) 10 | '-1 to 2' 11 | >>> str_interval(add_interval(interval(-1, 2), interval(4, 8))) 12 | '3 to 10' 13 | """, 14 | 'hidden': False, 15 | 'locked': False 16 | } 17 | ], 18 | 'scored': True, 19 | 'setup': r""" 20 | >>> import hw03 21 | >>> from hw03 import * 22 | """, 23 | 'teardown': '', 24 | 'type': 'doctest' 25 | }, 26 | { 27 | 'cases': [ 28 | { 29 | 'code': r""" 30 | >>> # Testing for abstraction violations 31 | >>> # Your code should not check for which implementation is used 32 | >>> str_interval(interval(-1, 2)) 33 | '-1 to 2' 34 | >>> str_interval(add_interval(interval(-1, 2), interval(4, 8))) 35 | '3 to 10' 36 | """, 37 | 'hidden': False, 38 | 'locked': False 39 | } 40 | ], 41 | 'scored': True, 42 | 'setup': r""" 43 | >>> import hw03 44 | >>> old_abstraction = hw03.interval, hw03.lower_bound, hw03.upper_bound 45 | >>> hw03.interval = lambda a, b: lambda x: a if x == 0 else b 46 | >>> hw03.lower_bound = lambda s: s(0) 47 | >>> hw03.upper_bound = lambda s: s(1) 48 | >>> from hw03 import * 49 | """, 50 | 'teardown': r""" 51 | >>> hw03.interval, hw03.lower_bound, hw03.upper_bound = old_abstraction 52 | """, 53 | 'type': 'doctest' 54 | } 55 | ] 56 | } 57 | -------------------------------------------------------------------------------- /homework/hw03/tests/mul_interval.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'mul_interval', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> str_interval(mul_interval(interval(-1, 2), interval(4, 8))) 10 | '-8 to 16' 11 | """, 12 | 'hidden': False, 13 | 'locked': False 14 | } 15 | ], 16 | 'scored': True, 17 | 'setup': r""" 18 | >>> import hw03 19 | >>> from hw03 import * 20 | """, 21 | 'teardown': '', 22 | 'type': 'doctest' 23 | }, 24 | { 25 | 'cases': [ 26 | { 27 | 'code': r""" 28 | >>> # Testing for abstraction violations 29 | >>> # Your code should not check for which implementation is used 30 | >>> str_interval(mul_interval(interval(-1, 2), interval(4, 8))) 31 | '-8 to 16' 32 | """, 33 | 'hidden': False, 34 | 'locked': False 35 | } 36 | ], 37 | 'scored': True, 38 | 'setup': r""" 39 | >>> import hw03 40 | >>> old_abstraction = hw03.interval, hw03.lower_bound, hw03.upper_bound 41 | >>> hw03.interval = lambda a, b: lambda x: a if x == 0 else b 42 | >>> hw03.lower_bound = lambda s: s(0) 43 | >>> hw03.upper_bound = lambda s: s(1) 44 | >>> from hw03 import * 45 | """, 46 | 'teardown': r""" 47 | >>> hw03.interval, hw03.lower_bound, hw03.upper_bound = old_abstraction 48 | """, 49 | 'type': 'doctest' 50 | } 51 | ] 52 | } 53 | -------------------------------------------------------------------------------- /homework/hw03/tests/polynomial.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'polynomial', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> str_interval(polynomial(interval(0, 2), [-1, 3, -2])) 10 | '-3 to 0.125' 11 | >>> str_interval(polynomial(interval(1, 3), [1, -3, 2])) 12 | '0 to 10' 13 | >>> str_interval(polynomial(interval(0.5, 2.25), [10, 24, -6, -8, 3])) 14 | '18.0 to 23.0' 15 | """, 16 | 'hidden': False, 17 | 'locked': False 18 | } 19 | ], 20 | 'scored': True, 21 | 'setup': r""" 22 | >>> import hw03 23 | >>> from hw03 import * 24 | """, 25 | 'teardown': '', 26 | 'type': 'doctest' 27 | }, 28 | { 29 | 'cases': [ 30 | { 31 | 'code': r""" 32 | >>> # Testing for abstraction violations 33 | >>> # Your code should not check for which implementation is used 34 | >>> str_interval(polynomial(interval(0, 2), [-1, 3, -2])) 35 | '-3 to 0.125' 36 | >>> str_interval(polynomial(interval(1, 3), [1, -3, 2])) 37 | '0 to 10' 38 | >>> str_interval(polynomial(interval(0.5, 2.25), [10, 24, -6, -8, 3])) 39 | '18.0 to 23.0' 40 | """, 41 | 'hidden': False, 42 | 'locked': False 43 | } 44 | ], 45 | 'scored': True, 46 | 'setup': r""" 47 | >>> import hw03 48 | >>> old_abstraction = hw03.interval, hw03.lower_bound, hw03.upper_bound 49 | >>> hw03.interval = lambda a, b: lambda x: a if x == 0 else b 50 | >>> hw03.lower_bound = lambda s: s(0) 51 | >>> hw03.upper_bound = lambda s: s(1) 52 | >>> from hw03 import * 53 | """, 54 | 'teardown': r""" 55 | >>> hw03.interval, hw03.lower_bound, hw03.upper_bound = old_abstraction 56 | """, 57 | 'type': 'doctest' 58 | } 59 | ] 60 | } 61 | -------------------------------------------------------------------------------- /homework/hw03/tests/quadratic.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'quadratic', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> str_interval(quadratic(interval(0, 2), -2, 3, -1)) 10 | '-3 to 0.125' 11 | >>> str_interval(quadratic(interval(1, 3), 2, -3, 1)) 12 | '0 to 10' 13 | """, 14 | 'hidden': False, 15 | 'locked': False 16 | } 17 | ], 18 | 'scored': True, 19 | 'setup': r""" 20 | >>> import hw03 21 | >>> from hw03 import * 22 | """, 23 | 'teardown': '', 24 | 'type': 'doctest' 25 | }, 26 | { 27 | 'cases': [ 28 | { 29 | 'code': r""" 30 | >>> # Testing for abstraction violations 31 | >>> # Your code should not check for which implementation is used 32 | >>> str_interval(quadratic(interval(0, 2), -2, 3, -1)) 33 | '-3 to 0.125' 34 | >>> str_interval(quadratic(interval(1, 3), 2, -3, 1)) 35 | '0 to 10' 36 | """, 37 | 'hidden': False, 38 | 'locked': False 39 | } 40 | ], 41 | 'scored': True, 42 | 'setup': r""" 43 | >>> import hw03 44 | >>> old_abstraction = hw03.interval, hw03.lower_bound, hw03.upper_bound 45 | >>> hw03.interval = lambda a, b: lambda x: a if x == 0 else b 46 | >>> hw03.lower_bound = lambda s: s(0) 47 | >>> hw03.upper_bound = lambda s: s(1) 48 | >>> from hw03 import * 49 | """, 50 | 'teardown': r""" 51 | >>> hw03.interval, hw03.lower_bound, hw03.upper_bound = old_abstraction 52 | """, 53 | 'type': 'doctest' 54 | } 55 | ] 56 | } 57 | -------------------------------------------------------------------------------- /homework/hw03/tests/sub_interval.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'sub_interval', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> str_interval(sub_interval(interval(-1, 2), interval(4, 8))) 10 | '-9 to -2' 11 | """, 12 | 'hidden': False, 13 | 'locked': False 14 | } 15 | ], 16 | 'scored': True, 17 | 'setup': r""" 18 | >>> import hw03 19 | >>> from hw03 import * 20 | """, 21 | 'teardown': '', 22 | 'type': 'doctest' 23 | }, 24 | { 25 | 'cases': [ 26 | { 27 | 'code': r""" 28 | >>> # Testing for abstraction violations 29 | >>> # Your code should not check for which implementation is used 30 | >>> str_interval(sub_interval(interval(-1, 2), interval(4, 8))) 31 | '-9 to -2' 32 | """, 33 | 'hidden': False, 34 | 'locked': False 35 | } 36 | ], 37 | 'scored': True, 38 | 'setup': r""" 39 | >>> import hw03 40 | >>> old_abstraction = hw03.interval, hw03.lower_bound, hw03.upper_bound 41 | >>> hw03.interval = lambda a, b: lambda x: a if x == 0 else b 42 | >>> hw03.lower_bound = lambda s: s(0) 43 | >>> hw03.upper_bound = lambda s: s(1) 44 | >>> from hw03 import * 45 | """, 46 | 'teardown': r""" 47 | >>> hw03.interval, hw03.lower_bound, hw03.upper_bound = old_abstraction 48 | """, 49 | 'type': 'doctest' 50 | } 51 | ] 52 | } 53 | -------------------------------------------------------------------------------- /homework/hw04/hw04.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Homework 4", 3 | "endpoint": "cal/cs61a/fa20/hw04", 4 | "src": [ 5 | "hw04.py" 6 | ], 7 | "tests": { 8 | "hw*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "make_withdraw", 13 | "make_bank", 14 | "repeated", 15 | "permutations" 16 | ], 17 | "protocols": [ 18 | "restore", 19 | "file_contents", 20 | "analytics", 21 | "unlock", 22 | "grading", 23 | "backup" 24 | ] 25 | } -------------------------------------------------------------------------------- /homework/hw04/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw04/ok -------------------------------------------------------------------------------- /homework/hw05/hw05.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Homework 5", 3 | "endpoint": "cal/cs61a/fa20/hw05", 4 | "src": [ 5 | "hw05.py" 6 | ], 7 | "tests": { 8 | "hw*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "VendingMachine", 13 | "Mint", 14 | "store_digits" 15 | ], 16 | "protocols": [ 17 | "restore", 18 | "file_contents", 19 | "analytics", 20 | "unlock", 21 | "grading", 22 | "backup" 23 | ] 24 | } -------------------------------------------------------------------------------- /homework/hw05/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw05/ok -------------------------------------------------------------------------------- /homework/hw06/hw06.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Homework 6", 3 | "endpoint": "cal/cs61a/fa20/hw06", 4 | "src": [ 5 | "hw06.py", 6 | "hw06.scm" 7 | ], 8 | "tests": { 9 | "hw*.py": "doctest", 10 | "tests/*.py": "ok_test" 11 | }, 12 | "default_tests": [ 13 | "cadr-caddr", 14 | "sign", 15 | "pow" 16 | ], 17 | "protocols": [ 18 | "restore", 19 | "file_contents", 20 | "grading", 21 | "analytics", 22 | "unlock", 23 | "backup" 24 | ] 25 | } -------------------------------------------------------------------------------- /homework/hw06/hw06.scm: -------------------------------------------------------------------------------- 1 | (define (cddr s) 2 | (cdr (cdr s))) 3 | 4 | 5 | (define (cadr s) 6 | (car (cdr s)) 7 | ) 8 | 9 | (define (caddr s) 10 | (car (cdr (cdr s))) 11 | ) 12 | 13 | 14 | (define (sign num) 15 | (cond 16 | ((< num 0) -1) 17 | ((= num 0) 0) 18 | ((> num 0) 1) 19 | ) 20 | ) 21 | 22 | 23 | (define (square x) (* x x)) 24 | 25 | (define (pow x y) 26 | (begin 27 | (cond 28 | ((= y 0) 1) 29 | ((= y 1) x) 30 | (else 31 | (if (even? y) 32 | (square (pow x (/ y 2))) 33 | (* x (square (pow x (/ (- y 1) 2 34 | ) 35 | ) 36 | ) 37 | ) 38 | ) 39 | ) 40 | ) 41 | ) 42 | ) -------------------------------------------------------------------------------- /homework/hw06/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw06/ok -------------------------------------------------------------------------------- /homework/hw07/hw07.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Homework 7", 3 | "endpoint": "cal/cs61a/fa20/hw07", 4 | "src": [ 5 | "hw07.scm" 6 | ], 7 | "tests": { 8 | "hw*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "filter_lst", 13 | "interleave", 14 | "accumulate", 15 | "no_repeats" 16 | ], 17 | "protocols": [ 18 | "restore", 19 | "file_contents", 20 | "grading", 21 | "analytics", 22 | "unlock", 23 | "backup" 24 | ] 25 | } -------------------------------------------------------------------------------- /homework/hw07/hw07.scm: -------------------------------------------------------------------------------- 1 | (define (filter-lst fn lst) 2 | (if (null? lst) 3 | nil 4 | (if (fn (car lst)) 5 | (cons (car lst) (filter-lst fn (cdr lst))) 6 | (filter-lst fn (cdr lst)) 7 | ) 8 | ) 9 | ) 10 | 11 | ;;; Tests 12 | (define (even? x) 13 | (= (modulo x 2) 0)) 14 | (filter-lst even? '(0 1 1 2 3 5 8)) 15 | ; expect (0 2 8) 16 | 17 | 18 | (define (interleave first second) 19 | (cond 20 | ((null? first) second) 21 | ((null? second) first) 22 | (else (cons (car first) (cons (car second) 23 | (interleave (cdr first) (cdr second)) 24 | ) 25 | )) 26 | ) 27 | ) 28 | 29 | (interleave (list 1 3 5) (list 2 4 6)) 30 | ; expect (1 2 3 4 5 6) 31 | 32 | (interleave (list 1 3 5) nil) 33 | ; expect (1 3 5) 34 | 35 | (interleave (list 1 3 5) (list 2 4)) 36 | ; expect (1 2 3 4 5) 37 | 38 | 39 | (define (accumulate combiner start n term) 40 | (if (= n 0) 41 | start 42 | (combiner (term n) (accumulate combiner start (- n 1) term)) 43 | ) 44 | ) 45 | 46 | 47 | (define (no-repeats lst) 48 | (if (null? lst) 49 | nil 50 | (cons (car lst) 51 | (no-repeats 52 | (filter-lst 53 | (lambda (x) (not (= x (car lst)))) 54 | (cdr lst) 55 | ) 56 | ) 57 | ) 58 | ) 59 | ) 60 | -------------------------------------------------------------------------------- /homework/hw07/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw07/ok -------------------------------------------------------------------------------- /homework/hw08/hw08.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Homework 8", 3 | "endpoint": "cal/cs61a/fa20/hw08", 4 | "src": [ 5 | "hw08.scm" 6 | ], 7 | "tests": { 8 | "hw*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "derive-sum", 13 | "derive-product", 14 | "wwsd-quasiquote", 15 | "wwsd-eval_apply" 16 | ], 17 | "protocols": [ 18 | "restore", 19 | "file_contents", 20 | "grading", 21 | "analytics", 22 | "unlock", 23 | "backup" 24 | ] 25 | } -------------------------------------------------------------------------------- /homework/hw08/hw08.scm: -------------------------------------------------------------------------------- 1 | (define (cadr s) (car (cdr s))) 2 | (define (caddr s) (car (cdr (cdr s)))) 3 | 4 | ; derive returns the derivative of EXPR with respect to VAR 5 | (define (derive expr var) 6 | (cond ((number? expr) 0) 7 | ((variable? expr) (if (same-variable? expr var) 1 0)) 8 | ((sum? expr) (derive-sum expr var)) 9 | ((product? expr) (derive-product expr var)) 10 | ((exp? expr) (derive-exp expr var)) 11 | (else 'Error))) 12 | 13 | ; Variables are represented as symbols 14 | (define (variable? x) (symbol? x)) 15 | (define (same-variable? v1 v2) 16 | (and (variable? v1) (variable? v2) (eq? v1 v2))) 17 | 18 | ; Numbers are compared with = 19 | (define (=number? expr num) 20 | (and (number? expr) (= expr num))) 21 | 22 | ; Sums are represented as lists that start with +. 23 | (define (make-sum a1 a2) 24 | (cond ((=number? a1 0) a2) 25 | ((=number? a2 0) a1) 26 | ((and (number? a1) (number? a2)) (+ a1 a2)) 27 | (else (list '+ a1 a2)))) 28 | (define (sum? x) 29 | (and (list? x) (eq? (car x) '+))) 30 | (define (first-operand s) (cadr s)) 31 | (define (second-operand s) (caddr s)) 32 | 33 | ; Products are represented as lists that start with *. 34 | (define (make-product m1 m2) 35 | (cond ((or (=number? m1 0) (=number? m2 0)) 0) 36 | ((=number? m1 1) m2) 37 | ((=number? m2 1) m1) 38 | ((and (number? m1) (number? m2)) (* m1 m2)) 39 | (else (list '* m1 m2)))) 40 | (define (product? x) 41 | (and (list? x) (eq? (car x) '*))) 42 | ; You can access the operands from the expressions with 43 | ; first-operand and second-operand 44 | (define (first-operand p) (cadr p)) 45 | (define (second-operand p) (caddr p)) 46 | 47 | (define (derive-sum expr var) 48 | (make-sum 49 | (derive (first-operand expr) var) 50 | (derive (second-operand expr) var) 51 | ) 52 | ) 53 | 54 | (define (derive-product expr var) 55 | (make-sum 56 | (make-product 57 | (derive (first-operand expr) var) 58 | (second-operand expr) 59 | ) 60 | (make-product 61 | (derive (second-operand expr) var) 62 | (first-operand expr) 63 | ) 64 | ) 65 | ) 66 | 67 | ; Exponentiations are represented as lists that start with ^. 68 | (define (make-exp base exponent) 69 | (cond ((=number? exponent 0) 1) 70 | ((=number? exponent 1) base) 71 | ((number? base) (expt base exponent)) 72 | (else (list '^ base exponent)) 73 | ) 74 | ) 75 | 76 | (define (exp? exp) 77 | (and (list? exp) (eq? (car exp) '^)) 78 | ) 79 | 80 | (define x^2 (make-exp 'x 2)) 81 | (define x^3 (make-exp 'x 3)) 82 | 83 | (define (derive-exp exp var) 84 | (make-product 85 | (second-operand exp 86 | ) 87 | (make-exp 88 | (first-operand exp) 89 | (- (second-operand exp) 1) 90 | ) 91 | ) 92 | ) -------------------------------------------------------------------------------- /homework/hw08/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw08/ok -------------------------------------------------------------------------------- /homework/hw09/hw09.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Homework 9", 3 | "endpoint": "cal/cs61a/fa20/hw09", 4 | "src": [ 5 | "hw09.sql", 6 | "hw09.scm" 7 | ], 8 | "tests": { 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "size_of_dogs", 13 | "by_parent_height", 14 | "sentences" 15 | ], 16 | "protocols": [ 17 | "restore", 18 | "file_contents", 19 | "unlock", 20 | "grading", 21 | "analytics", 22 | "backup" 23 | ] 24 | } -------------------------------------------------------------------------------- /homework/hw09/hw09.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE parents AS 2 | SELECT "abraham" AS parent, "barack" AS child UNION 3 | SELECT "abraham" , "clinton" UNION 4 | SELECT "delano" , "herbert" UNION 5 | SELECT "fillmore" , "abraham" UNION 6 | SELECT "fillmore" , "delano" UNION 7 | SELECT "fillmore" , "grover" UNION 8 | SELECT "eisenhower" , "fillmore"; 9 | 10 | CREATE TABLE dogs AS 11 | SELECT "abraham" AS name, "long" AS fur, 26 AS height UNION 12 | SELECT "barack" , "short" , 52 UNION 13 | SELECT "clinton" , "long" , 47 UNION 14 | SELECT "delano" , "long" , 46 UNION 15 | SELECT "eisenhower" , "short" , 35 UNION 16 | SELECT "fillmore" , "curly" , 32 UNION 17 | SELECT "grover" , "short" , 28 UNION 18 | SELECT "herbert" , "curly" , 31; 19 | 20 | CREATE TABLE sizes AS 21 | SELECT "toy" AS size, 24 AS min, 28 AS max UNION 22 | SELECT "mini" , 28 , 35 UNION 23 | SELECT "medium" , 35 , 45 UNION 24 | SELECT "standard" , 45 , 60; 25 | 26 | 27 | -- The size of each dog 28 | CREATE TABLE size_of_dogs AS 29 | SELECT name, size 30 | FROM dogs as d, sizes as s 31 | WHERE d.height > s.min and d.height <= s.max; 32 | 33 | 34 | -- All dogs with parents ordered by decreasing height of their parent 35 | CREATE TABLE by_parent_height AS 36 | SELECT child 37 | FROM dogs as d, parents as p 38 | WHERE p.parent = d.name 39 | ORDER BY -d.height; 40 | 41 | 42 | -- Filling out this helper table is optional 43 | CREATE TABLE siblings AS 44 | SELECT p1.child as name1, p2.child as name2 45 | FROM parents as p1, parents as p2 46 | WHERE p1.parent = p2.parent and p1.child < p2.child; 47 | 48 | -- Sentences about siblings that are the same size 49 | CREATE TABLE sentences AS 50 | SELECT "The two siblings, "||s.name1||" plus "||s.name2||" have the same size: "||d1.size 51 | FROM siblings as s, size_of_dogs as d1, size_of_dogs as d2 52 | WHERE s.name1 = d1.name and s.name2 = d2.name and d1.size = d2.size; 53 | -------------------------------------------------------------------------------- /homework/hw09/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/homework/hw09/ok -------------------------------------------------------------------------------- /lab/lab00/lab00.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 0", 3 | "endpoint": "cal/cs61a/fa20/lab00", 4 | "src": [ 5 | "lab00.py" 6 | ], 7 | "tests": { 8 | "lab*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "twenty_twenty", 13 | "python-basics" 14 | ], 15 | "protocols": [ 16 | "restore", 17 | "file_contents", 18 | "analytics", 19 | "unlock", 20 | "grading", 21 | "backup" 22 | ] 23 | } -------------------------------------------------------------------------------- /lab/lab00/lab00.py: -------------------------------------------------------------------------------- 1 | def twenty_twenty(): 2 | """Come up with the most creative expression that evaluates to 2020, 3 | using only numbers and the +, *, and - operators. 4 | 5 | >>> twenty_twenty() 6 | 2020 7 | """ 8 | return -(1-145)*14+(-11-4+5+14) 9 | -------------------------------------------------------------------------------- /lab/lab00/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab00/ok -------------------------------------------------------------------------------- /lab/lab00/tests/python-basics.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Python Basics', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> 10 + 2 10 | 12 11 | >>> 7 / 2 12 | 3.5 13 | >>> 7 // 2 14 | 3 15 | >>> 7 % 2 # 7 modulo 2, the remainder when dividing 7 by 2. 16 | 1 17 | """, 18 | 'hidden': False, 19 | 'locked': False 20 | } 21 | ], 22 | 'scored': False, 23 | 'type': 'wwpp' 24 | }, 25 | { 26 | 'cases': [ 27 | { 28 | 'code': r""" 29 | >>> x = 20 30 | >>> x + 2 31 | 22 32 | >>> x 33 | 20 34 | >>> y = 5 35 | >>> y = y + 3 36 | >>> y * 2 37 | 16 38 | >>> y = y // 4 39 | >>> y + x 40 | 22 41 | """, 42 | 'hidden': False, 43 | 'locked': False 44 | } 45 | ], 46 | 'scored': False, 47 | 'type': 'wwpp' 48 | } 49 | ] 50 | } 51 | -------------------------------------------------------------------------------- /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 | result = 1 14 | while k > 0: 15 | result *= n 16 | k -= 1 17 | n -= 1 18 | return result 19 | 20 | 21 | def sum_digits(y): 22 | """Sum all the digits of y. 23 | 24 | >>> sum_digits(10) # 1 + 0 = 1 25 | 1 26 | >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 27 | 12 28 | >>> sum_digits(1234567890) 29 | 45 30 | >>> a = sum_digits(123) # make sure that you are using return rather than print 31 | >>> a 32 | 6 33 | """ 34 | sum = 0 35 | while y > 0: 36 | last_digit = y % 10 37 | sum += last_digit 38 | y = (y - last_digit) // 10 39 | return sum 40 | 41 | 42 | 43 | def double_eights(n): 44 | """Return true if n has two eights in a row. 45 | >>> double_eights(8) 46 | False 47 | >>> double_eights(88) 48 | True 49 | >>> double_eights(2882) 50 | True 51 | >>> double_eights(880088) 52 | True 53 | >>> double_eights(12345) 54 | False 55 | >>> double_eights(80808080) 56 | False 57 | """ 58 | while n > 0: 59 | if n % 10 == 8: 60 | n = n // 10 61 | if n % 10 == 8: 62 | return True 63 | else: 64 | n = n // 10 65 | return False 66 | -------------------------------------------------------------------------------- /lab/lab01/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab01/ok -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /lab/lab02/lab02.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 2", 3 | "endpoint": "cal/cs61a/fa20/lab02", 4 | "src": [ 5 | "lab02.py" 6 | ], 7 | "tests": { 8 | "lab*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "lambda", 13 | "hof-wwpd", 14 | "lambda_curry2", 15 | "count_cond" 16 | ], 17 | "protocols": [ 18 | "restore", 19 | "file_contents", 20 | "analytics", 21 | "unlock", 22 | "grading", 23 | "backup" 24 | ] 25 | } -------------------------------------------------------------------------------- /lab/lab02/lab02.py: -------------------------------------------------------------------------------- 1 | 2 | def lambda_curry2(func): 3 | """ 4 | Returns a Curried version of a two-argument function FUNC. 5 | >>> from operator import add, mul, mod 6 | >>> curried_add = lambda_curry2(add) 7 | >>> add_three = curried_add(3) 8 | >>> add_three(5) 9 | 8 10 | >>> curried_mul = lambda_curry2(mul) 11 | >>> mul_5 = curried_mul(5) 12 | >>> mul_5(42) 13 | 210 14 | >>> lambda_curry2(mod)(123)(10) 15 | 3 16 | """ 17 | return lambda x: lambda y: func(x, y) 18 | 19 | 20 | 21 | def count_cond(condition): 22 | """Returns a function with one parameter N that counts all the numbers from 23 | 1 to N that satisfy the two-argument predicate function Condition, where 24 | the first argument for Condition is N and the second argument is the 25 | number from 1 to N. 26 | 27 | >>> count_factors = count_cond(lambda n, i: n % i == 0) 28 | >>> count_factors(2) # 1, 2 29 | 2 30 | >>> count_factors(4) # 1, 2, 4 31 | 3 32 | >>> count_factors(12) # 1, 2, 3, 4, 6, 12 33 | 6 34 | 35 | >>> is_prime = lambda n, i: count_factors(i) == 2 36 | >>> count_primes = count_cond(is_prime) 37 | >>> count_primes(2) # 2 38 | 1 39 | >>> count_primes(3) # 2, 3 40 | 2 41 | >>> count_primes(4) # 2, 3 42 | 2 43 | >>> count_primes(5) # 2, 3, 5 44 | 3 45 | >>> count_primes(20) # 2, 3, 5, 7, 11, 13, 17, 19 46 | 8 47 | """ 48 | def count(N): 49 | i, counts = 1, 0 50 | while i <= N: 51 | if condition(N, i): 52 | counts += 1 53 | i += 1 54 | return counts 55 | return count 56 | 57 | 58 | 59 | def compose1(f, g): 60 | """Return the composition function which given x, computes f(g(x)). 61 | 62 | >>> add_one = lambda x: x + 1 # adds one to x 63 | >>> square = lambda x: x**2 64 | >>> a1 = compose1(square, add_one) # (x + 1)^2 65 | >>> a1(4) 66 | 25 67 | >>> mul_three = lambda x: x * 3 # multiplies 3 to x 68 | >>> a2 = compose1(mul_three, a1) # ((x + 1)^2) * 3 69 | >>> a2(4) 70 | 75 71 | >>> a2(5) 72 | 108 73 | """ 74 | return lambda x: f(g(x)) 75 | 76 | def composite_identity(f, g): 77 | """ 78 | Return a function with one parameter x that returns True if f(g(x)) is 79 | equal to g(f(x)). You can assume the result of g(x) is a valid input for f 80 | and vice versa. 81 | 82 | >>> add_one = lambda x: x + 1 # adds one to x 83 | >>> square = lambda x: x**2 84 | >>> b1 = composite_identity(square, add_one) 85 | >>> b1(0) # (0 + 1)^2 == 0^2 + 1 86 | True 87 | >>> b1(4) # (4 + 1)^2 != 4^2 + 1 88 | False 89 | """ 90 | # def is_identity(x): 91 | # return compose1(f, g)(x) == compose1(g, f)(x) 92 | # return is_identity 93 | return lambda x: compose1(f, g)(x) == compose1(g, f)(x) 94 | 95 | 96 | 97 | def cycle(f1, f2, f3): 98 | """Returns a function that is itself a higher-order function. 99 | 100 | >>> def add1(x): 101 | ... return x + 1 102 | >>> def times2(x): 103 | ... return x * 2 104 | >>> def add3(x): 105 | ... return x + 3 106 | >>> my_cycle = cycle(add1, times2, add3) 107 | >>> identity = my_cycle(0) 108 | >>> identity(5) 109 | 5 110 | >>> add_one_then_double = my_cycle(2) 111 | >>> add_one_then_double(1) 112 | 4 113 | >>> do_all_functions = my_cycle(3) 114 | >>> do_all_functions(2) 115 | 9 116 | >>> do_more_than_a_cycle = my_cycle(4) 117 | >>> do_more_than_a_cycle(2) 118 | 10 119 | >>> do_two_cycles = my_cycle(6) 120 | >>> do_two_cycles(1) 121 | 19 122 | """ 123 | def process(n): 124 | # print("DEBUG: process n = ", n) 125 | def action(x): 126 | k = n 127 | # print("DEBUG: action n = ", n) 128 | while k > 0: 129 | no = (n - k ) % 3 130 | if no == 0: 131 | x = f1(x) 132 | elif no == 1: 133 | x = f2(x) 134 | elif no == 2: 135 | x = f3(x) 136 | k -= 1 137 | return x 138 | return action 139 | return process 140 | -------------------------------------------------------------------------------- /lab/lab02/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab02/ok -------------------------------------------------------------------------------- /lab/lab02/tests/hof-wwpd.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Higher Order Functions', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> def even(f): 10 | ... def odd(x): 11 | ... if x < 0: 12 | ... return f(-x) 13 | ... return f(x) 14 | ... return odd 15 | >>> steven = lambda x: x 16 | >>> stewart = even(steven) 17 | >>> stewart 18 | Function 19 | >>> stewart(61) 20 | 61 21 | >>> stewart(-4) 22 | 4 23 | """, 24 | 'hidden': False, 25 | 'locked': False 26 | }, 27 | { 28 | 'code': r""" 29 | >>> def cake(): 30 | ... print('beets') 31 | ... def pie(): 32 | ... print('sweets') 33 | ... return 'cake' 34 | ... return pie 35 | >>> chocolate = cake() 36 | beets 37 | >>> chocolate 38 | Function 39 | >>> chocolate() 40 | sweets 41 | 'cake' 42 | >>> more_chocolate, more_cake = chocolate(), cake 43 | sweets 44 | >>> more_chocolate 45 | 'cake' 46 | >>> def snake(x, y): 47 | ... if cake == more_cake: 48 | ... return chocolate 49 | ... else: 50 | ... return x + y 51 | >>> snake(10, 20) 52 | Function 53 | >>> snake(10, 20)() 54 | sweets 55 | 'cake' 56 | >>> cake = 'cake' 57 | >>> snake(10, 20) 58 | 30 59 | """, 60 | 'hidden': False, 61 | 'locked': False 62 | } 63 | ], 64 | 'scored': False, 65 | 'type': 'wwpp' 66 | } 67 | ] 68 | } 69 | -------------------------------------------------------------------------------- /lab/lab04/lab04.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 4", 3 | "endpoint": "cal/cs61a/fa20/lab04", 4 | "src": [ 5 | "lab04.py" 6 | ], 7 | "tests": { 8 | "lab*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "list-indexing", 13 | "skip_add", 14 | "summation", 15 | "paths", 16 | "max_subseq" 17 | ], 18 | "protocols": [ 19 | "restore", 20 | "file_contents", 21 | "unlock", 22 | "grading", 23 | "analytics", 24 | "backup" 25 | ] 26 | } -------------------------------------------------------------------------------- /lab/lab04/lab04.py: -------------------------------------------------------------------------------- 1 | LAB_SOURCE_FILE = __file__ 2 | 3 | 4 | 5 | this_file = __file__ 6 | 7 | def skip_add(n): 8 | """ Takes a number n and returns n + n-2 + n-4 + n-6 + ... + 0. 9 | 10 | >>> skip_add(5) # 5 + 3 + 1 + 0 11 | 9 12 | >>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0 13 | 30 14 | >>> # Do not use while/for loops! 15 | >>> from construct_check import check 16 | >>> # ban iteration 17 | >>> check(this_file, 'skip_add', 18 | ... ['While', 'For']) 19 | True 20 | """ 21 | if n <= 0: # Base case 22 | return 0 23 | else: # Recursive case 24 | return n + skip_add(n-2) 25 | 26 | 27 | def summation(n, term): 28 | 29 | """Return the sum of the first n terms in the sequence defined by term. 30 | Implement using recursion! 31 | 32 | >>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3 33 | 225 34 | >>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 35 | 54 36 | >>> summation(5, lambda x: 2**x) # 2^1 + 2^2 + 2^3 + 2^4 + 2^5 37 | 62 38 | >>> # Do not use while/for loops! 39 | >>> from construct_check import check 40 | >>> # ban iteration 41 | >>> check(this_file, 'summation', 42 | ... ['While', 'For']) 43 | True 44 | """ 45 | assert n >= 1 46 | if n == 1: 47 | return term(1) 48 | else: 49 | return term(n) + summation(n-1, term) 50 | 51 | 52 | def paths(m, n): 53 | """Return the number of paths from one corner of an 54 | M by N grid to the opposite corner. 55 | 56 | >>> paths(2, 2) 57 | 2 58 | >>> paths(5, 7) 59 | 210 60 | >>> paths(117, 1) 61 | 1 62 | >>> paths(1, 157) 63 | 1 64 | """ 65 | if m == 1 or n == 1: 66 | return 1 67 | elif m ==0 or n == 0: 68 | return 0 69 | else: 70 | return paths(m-1, n) + paths(m, n-1) 71 | 72 | 73 | 74 | def max_subseq(n, t): 75 | """ 76 | Return the maximum subsequence of length at most t that can be found in the given number n. 77 | For example, for n = 20125 and t = 3, we have that the subsequences are 78 | 2 79 | 0 80 | 1 81 | 2 82 | 5 83 | 20 84 | 21 85 | 22 86 | 25 87 | 01 88 | 02 89 | 05 90 | 12 91 | 15 92 | 25 93 | 201 94 | 202 95 | 205 96 | 212 97 | 215 98 | 225 99 | 012 100 | 015 101 | 025 102 | 125 103 | and of these, the maxumum number is 225, so our answer is 225. 104 | 105 | >>> max_subseq(20125, 3) 106 | 225 107 | >>> max_subseq(20125, 5) 108 | 20125 109 | >>> max_subseq(20125, 6) # note that 20125 == 020125 110 | 20125 111 | >>> max_subseq(12345, 3) 112 | 345 113 | >>> max_subseq(12345, 0) # 0 is of length 0 114 | 0 115 | >>> max_subseq(12345, 1) 116 | 5 117 | """ 118 | if t == 0: 119 | return 0 120 | elif n < 10: 121 | return n 122 | else: 123 | all_but_last, last = n //10, n % 10 124 | use_digit = max_subseq(all_but_last, t-1) * 10 + last 125 | not_use_digit = max_subseq(all_but_last, t) 126 | return max(use_digit, not_use_digit) 127 | 128 | 129 | def add_chars(w1, w2): 130 | """ 131 | Return a string containing the characters you need to add to w1 to get w2. 132 | 133 | You may assume that w1 is a subsequence of w2. 134 | 135 | >>> add_chars("owl", "howl") 136 | 'h' 137 | >>> add_chars("want", "wanton") 138 | 'on' 139 | >>> add_chars("rat", "radiate") 140 | 'diae' 141 | >>> add_chars("a", "prepare") 142 | 'prepre' 143 | >>> add_chars("resin", "recursion") 144 | 'curo' 145 | >>> add_chars("fin", "effusion") 146 | 'efuso' 147 | >>> add_chars("coy", "cacophony") 148 | 'acphon' 149 | >>> from construct_check import check 150 | >>> # ban iteration and sets 151 | >>> check(LAB_SOURCE_FILE, 'add_chars', 152 | ... ['For', 'While', 'Set', 'SetComp']) # Must use recursion 153 | True 154 | """ 155 | def add_chars_helper(w1, w2, add=''): 156 | if len(w1) == len(w2): 157 | return add 158 | elif len(w1) == 0: 159 | add += w2 160 | return add 161 | else: 162 | if w1[0] == w2[0]: 163 | return add_chars_helper(w1[1:], w2[1:], add) 164 | else: 165 | return add_chars_helper(w1, w2[1:], add+w2[0]) 166 | 167 | return add_chars_helper(w1, w2) 168 | -------------------------------------------------------------------------------- /lab/lab04/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab04/ok -------------------------------------------------------------------------------- /lab/lab04/tests/list-indexing.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'List Indexing', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> x = [1, 3, [5, 7], 9] # Write the expression that indexes into x to output the 7 10 | x[2][1] 11 | >>> x = [[3, [5, 7], 9]] # Write the expression that indexes into x to output the 7 12 | x[0][1][1] 13 | """, 14 | 'hidden': False, 15 | 'locked': False 16 | } 17 | ], 18 | 'scored': False, 19 | 'type': 'wwpp' 20 | }, 21 | { 22 | 'cases': [ 23 | { 24 | 'code': r""" 25 | >>> lst = [3, 2, 7, [84, 83, 82]] 26 | >>> lst[4] 27 | Error 28 | >>> lst[3][0] 29 | 84 30 | """, 31 | 'hidden': False, 32 | 'locked': False 33 | } 34 | ], 35 | 'scored': False, 36 | 'type': 'wwpp' 37 | } 38 | ] 39 | } 40 | -------------------------------------------------------------------------------- /lab/lab05/lab05.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 5", 3 | "endpoint": "cal/cs61a/fa20/lab05", 4 | "src": [ 5 | "lab05.py" 6 | ], 7 | "tests": { 8 | "lab*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "couple", 13 | "distance", 14 | "closer_city", 15 | "check_city_abstraction", 16 | "berry_finder", 17 | "sprout_leaves", 18 | "check_abstraction" 19 | ], 20 | "protocols": [ 21 | "restore", 22 | "file_contents", 23 | "unlock", 24 | "grading", 25 | "analytics", 26 | "backup" 27 | ] 28 | } -------------------------------------------------------------------------------- /lab/lab05/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab05/ok -------------------------------------------------------------------------------- /lab/lab06/lab06.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 6", 3 | "endpoint": "cal/cs61a/fa20/lab06", 4 | "src": [ 5 | "lab06.py" 6 | ], 7 | "tests": { 8 | "lab*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "make_adder_inc", 13 | "make_fib", 14 | "insert_items", 15 | "list-mutation" 16 | ], 17 | "protocols": [ 18 | "restore", 19 | "file_contents", 20 | "unlock", 21 | "grading", 22 | "analytics", 23 | "backup" 24 | ] 25 | } -------------------------------------------------------------------------------- /lab/lab06/lab06.py: -------------------------------------------------------------------------------- 1 | this_file = __file__ 2 | 3 | 4 | def make_adder_inc(a): 5 | """ 6 | >>> adder1 = make_adder_inc(5) 7 | >>> adder2 = make_adder_inc(6) 8 | >>> adder1(2) 9 | 7 10 | >>> adder1(2) # 5 + 2 + 1 11 | 8 12 | >>> adder1(10) # 5 + 10 + 2 13 | 17 14 | >>> [adder1(x) for x in [1, 2, 3]] 15 | [9, 11, 13] 16 | >>> adder2(5) 17 | 11 18 | """ 19 | def adder_inc(b): 20 | nonlocal a 21 | a += 1 22 | return a + b - 1 23 | return adder_inc 24 | 25 | 26 | def make_fib(): 27 | """Returns a function that returns the next Fibonacci number 28 | every time it is called. 29 | 30 | >>> fib = make_fib() 31 | >>> fib() 32 | 0 33 | >>> fib() 34 | 1 35 | >>> fib() 36 | 1 37 | >>> fib() 38 | 2 39 | >>> fib() 40 | 3 41 | >>> fib2 = make_fib() 42 | >>> fib() + sum([fib2() for _ in range(5)]) 43 | 12 44 | >>> from construct_check import check 45 | >>> # Do not use lists in your implementation 46 | >>> check(this_file, 'make_fib', ['List']) 47 | True 48 | """ 49 | cur, next = 0, 0 50 | def next_fib(): 51 | nonlocal cur, next 52 | if next == 0: 53 | next += 1 54 | else: 55 | cur, next = next, cur + next 56 | return cur 57 | return next_fib 58 | 59 | 60 | def insert_items(lst, entry, elem): 61 | """ 62 | >>> test_lst = [1, 5, 8, 5, 2, 3] 63 | >>> new_lst = insert_items(test_lst, 5, 7) 64 | >>> new_lst 65 | [1, 5, 7, 8, 5, 7, 2, 3] 66 | >>> large_lst = [1, 4, 8] 67 | >>> large_lst2 = insert_items(large_lst, 4, 4) 68 | >>> large_lst2 69 | [1, 4, 4, 8] 70 | >>> large_lst3 = insert_items(large_lst2, 4, 6) 71 | >>> large_lst3 72 | [1, 4, 6, 4, 6, 8] 73 | >>> large_lst3 is large_lst 74 | True 75 | """ 76 | indexes = [k for k in range(len(lst)) if lst[k]==entry] 77 | for i in range(len(indexes)): 78 | insert_i = indexes[i] + i + 1 79 | lst[insert_i:insert_i] = [elem] 80 | return lst 81 | -------------------------------------------------------------------------------- /lab/lab06/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab06/ok -------------------------------------------------------------------------------- /lab/lab06/tests/list-mutation.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'List Mutation', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> lst = [5, 6, 7, 8] 10 | >>> lst.append(6) 11 | Nothing 12 | >>> lst 13 | [5, 6, 7, 8, 6] 14 | >>> lst.insert(0, 9) 15 | >>> lst 16 | [9, 5, 6, 7, 8, 6] 17 | >>> x = lst.pop(2) 18 | >>> lst 19 | [9, 5, 7, 8, 6] 20 | >>> lst.remove(x) 21 | >>> lst 22 | [9, 5, 7, 8] 23 | >>> a, b = lst, lst[:] 24 | >>> a is lst 25 | True 26 | >>> b == lst 27 | True 28 | >>> b is lst 29 | False 30 | """, 31 | 'hidden': False, 32 | 'locked': False 33 | } 34 | ], 35 | 'scored': False, 36 | 'type': 'wwpp' 37 | } 38 | ] 39 | } 40 | -------------------------------------------------------------------------------- /lab/lab07/car.py: -------------------------------------------------------------------------------- 1 | class Car(object): 2 | num_wheels = 4 3 | gas = 30 4 | headlights = 2 5 | size = 'Tiny' 6 | 7 | def __init__(self, make, model): 8 | self.make = make 9 | self.model = model 10 | self.color = 'No color yet. You need to paint me.' 11 | self.wheels = Car.num_wheels 12 | self.gas = Car.gas 13 | 14 | def paint(self, color): 15 | self.color = color 16 | return self.make + ' ' + self.model + ' is now ' + color 17 | 18 | def drive(self): 19 | if self.wheels < Car.num_wheels or self.gas <= 0: 20 | return 'Cannot drive!' 21 | self.gas -= 10 22 | return self.make + ' ' + self.model + ' goes vroom!' 23 | 24 | def pop_tire(self): 25 | if self.wheels > 0: 26 | self.wheels -= 1 27 | 28 | def fill_gas(self): 29 | self.gas += 20 30 | return 'Gas level: ' + str(self.gas) 31 | 32 | 33 | class MonsterTruck(Car): 34 | size = 'Monster' 35 | 36 | def rev(self): 37 | print('Vroom! This Monster Truck is huge!') 38 | 39 | def drive(self): 40 | self.rev() 41 | return Car.drive(self) 42 | -------------------------------------------------------------------------------- /lab/lab07/cardgame.py: -------------------------------------------------------------------------------- 1 | from classes import * 2 | from cards import * 3 | 4 | try: 5 | import readline 6 | except ImportError: 7 | pass 8 | 9 | ########### 10 | # Parsing # 11 | ########### 12 | 13 | def card_parse(line, handsize): 14 | tokens = line.split() 15 | if not tokens: 16 | raise SyntaxError('No command given') 17 | elif len(tokens) > 1: 18 | raise SyntaxError('Too many inputs') 19 | card_index = tokens.pop(0) 20 | if not card_index.isdigit(): 21 | raise SyntaxError('Wrong type of input') 22 | card_index = int(card_index) 23 | if card_index >= handsize or card_index < 0: 24 | raise SyntaxError('Invalid card number') 25 | return card_index 26 | 27 | def name_parse(line): 28 | if not line: 29 | raise SyntaxError('No command given') 30 | return line 31 | 32 | ######## 33 | # REPL # 34 | ######## 35 | 36 | def read_eval_print_loop(): 37 | while True: 38 | try: 39 | line = input('What is your name?> ') 40 | name = name_parse(line) 41 | break 42 | except (KeyboardInterrupt, EOFError, SystemExit): # If you ctrl-c or ctrl-d 43 | print('\nSee you next game!') 44 | return 45 | except SyntaxError as e: 46 | print('ERROR:', e) 47 | p1 = Player(player_deck, name) 48 | p2 = Player(opponent_deck, 'Opponent') 49 | print(WELCOME_MESSAGE) 50 | duel = Game(p1, p2) 51 | draw = True 52 | while True: 53 | if duel.game_won() == 1: 54 | print(WIN_MESSAGE) 55 | return 56 | elif duel.game_won() == 2: 57 | print(LOSE_MESSAGE) 58 | return 59 | print() 60 | try: 61 | if draw: 62 | p1.draw() 63 | p2.draw() 64 | else: 65 | draw = True 66 | p1.display_hand() 67 | print('Please enter the number next to the card you would like to play this round.') 68 | line = input('card> ') 69 | card_index = card_parse(line, len(p1.hand)) 70 | duel.play_round(p1.play(card_index), p2.play_random()) 71 | duel.display_scores() 72 | except (KeyboardInterrupt, EOFError, SystemExit): # If you ctrl-c or ctrl-d 73 | print('\nGood game. Bye!') 74 | return 75 | except AssertionError: # Deck out 76 | if p1.deck.is_empty() and p2.deck.is_empty(): 77 | print(TIE_MESSAGE) 78 | return 79 | elif p1.deck.is_empty(): 80 | print(PLAYER_DECKOUT_MESSAGE) 81 | return 82 | else: 83 | print(OPPONENT_DECKOUT_MESSAGE) 84 | return 85 | except SyntaxError as e: 86 | print('ERROR:', e) 87 | draw = False 88 | 89 | ################# 90 | # Configuration # 91 | ################# 92 | 93 | WELCOME_MESSAGE = """ 94 | Welcome to Magic: The Lambda-ing! 95 | 96 | Your code has taken on a mind of its own and has 97 | challenged you to a game of cards! If you need a refresher 98 | on the rules, check out the section on the lab page. 99 | 100 | Let's get this duel started, shall we? 101 | """ 102 | 103 | WIN_MESSAGE = """ 104 | You have vanquished your foe in a duel! 105 | 106 | Congratulations! You won this game of Magic: The Lambda-ing! 107 | """ 108 | 109 | LOSE_MESSAGE = """ 110 | You have been defeated by your foe in a duel! 111 | 112 | I'm sorry, you lost this game of Magic: The Lambda-ing. 113 | """ 114 | 115 | TIE_MESSAGE = """ 116 | You and your opponent have no cards left in your decks! 117 | 118 | You tied this game of Magic: The Lambda-ing. Who will win if you play again? 119 | """ 120 | 121 | PLAYER_DECKOUT_MESSAGE = """ 122 | You have no cards left in your deck! 123 | 124 | I'm sorry, you lost this game of Magic: The Lambda-ing. 125 | """ 126 | 127 | OPPONENT_DECKOUT_MESSAGE = """ 128 | Your opponent has no cards left in their deck! 129 | 130 | Congratulations! You won this game of Magic: The Lambda-ing! 131 | """ 132 | 133 | if __name__ == '__main__': 134 | read_eval_print_loop() 135 | 136 | -------------------------------------------------------------------------------- /lab/lab07/cards.py: -------------------------------------------------------------------------------- 1 | # All cards available in a standard deck. 2 | from classes import * 3 | 4 | #TAs 5 | sean = TACard('Sean, the Over-Caffeinated', 1000, 2300) 6 | jade = TACard('Jade, Singher of Songs', 1700, 1700) 7 | richard_r = TACard('Richard, Protector of Baby Yoda', 2100, 1800) 8 | griffin = TACard('Griffin, the Goblin Keeper', 1300, 1500) 9 | albert = TACard('Albert, Lethargy Incarnate', 1000, 2300) 10 | shayna = TACard('Shayna, Queen of the Bones', 1111, 2235) 11 | addison = TACard('Addison, from operator import add', 1000, 2000) 12 | cesar = TACard('Cesar, City Slicker', 1337, 2020) 13 | catherine = TACard('Catherine, Supporter of Cats', 1900, 1000) 14 | amrita = TACard('Amrita-tron 3000', 2150, 1750) 15 | 16 | #Tutors 17 | laryn = TutorCard('Laryn, Lord of Lambdas', 2300, 2300) 18 | parth = TutorCard('Parth, the Protector of Piazza', 1500, 2200) 19 | todd = TutorCard('Todd, Protector of Corgis', 2300, 1000) 20 | crystal = TutorCard('Crystal, Fat Bear Week 2020 Runner-Up', 2023, 1738) 21 | ben = TutorCard('Ben, the Panda stuck in an Infinite Loop', 1024, 2020) 22 | cyrus = TutorCard('Cyrus, King of Phonies', 1700, 2200) 23 | roy = TutorCard('Roy, Eater of Oranges', 2229, 2268) 24 | animesh = TutorCard('Animesh, without a cool hat', 1000, 2300) 25 | megan = TutorCard('Megan, Lord of the Kiwi Bots', 2000, 1100) 26 | yersultan = TutorCard('Yersultan, Yogurt Man', 1246, 1790) 27 | connie = TutorCard('Connie, Carb Connoisseur', 2123, 1029) 28 | jenny = TutorCard('Jenny, the Spy Among Other Jennys', 1500, 2000) 29 | jeffrey = TutorCard('Jeffrey, Freezer of Fruit', 2300, 1000) 30 | marie = TutorCard('Marie, Arbiter of Justice and Herald of Seraphs, True Heir to the Last Monarch of Ra’toth', 1150, 2200) 31 | linh = TutorCard('Linh, Phantom of the Classroom', 1919, 2299) 32 | benny = TutorCard('Benny, Practitioner of Day-Night Reversal', 1694, 2009) 33 | tim = TutorCard('Tim Tu, Tyrant Tutor of Twos', 2222, 2222) 34 | emma = TutorCard('Emma, the Perpetually Unrested', 2000, 1834) 35 | richard_z = TutorCard('Richard, Headband Merchant', 1337, 1614) 36 | brandon = TutorCard('Brandon, the Deadline Demon', 1250, 1000) 37 | daphne = TutorCard('Daphne, Daphrying Pan', 1801, 1350) 38 | jamie = TutorCard('Jamie, Anagrammer of Rice Or Sun', 2234, 1828) 39 | 40 | 41 | 42 | # Professors 43 | denero = ProfessorCard('John DeNero, Protector of Abstraction Barriers', 5000, 5000) 44 | 45 | # A standard deck contains all standard cards. 46 | standard_cards = [denero, sean, jade, richard_r, griffin, albert, shayna, addison, cesar, catherine, amrita, laryn, parth, todd, crystal, ben, cyrus, roy, animesh, megan, yersultan, connie, jenny, jeffrey, marie, linh, benny, tim, emma, richard_z, brandon, daphne, jamie] 47 | standard_deck = Deck(standard_cards) 48 | 49 | # The player and opponent's decks are the standard deck by default. 50 | player_deck = standard_deck.copy() 51 | opponent_deck = standard_deck.copy() 52 | 53 | -------------------------------------------------------------------------------- /lab/lab07/lab07.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 7", 3 | "endpoint": "cal/cs61a/fa20/lab07", 4 | "src": [ 5 | "lab07.py", 6 | "classes.py" 7 | ], 8 | "tests": { 9 | "lab*.py": "doctest", 10 | "tests/*.py": "ok_test", 11 | "classes.py": "doctest" 12 | }, 13 | "default_tests": [ 14 | "scale", 15 | "hailstone", 16 | "wwpd-car", 17 | "Card.__init__", 18 | "Card.power", 19 | "Player.__init__", 20 | "Player.draw", 21 | "Player.play" 22 | ], 23 | "protocols": [ 24 | "restore", 25 | "file_contents", 26 | "unlock", 27 | "grading", 28 | "analytics", 29 | "backup" 30 | ] 31 | } -------------------------------------------------------------------------------- /lab/lab07/lab07.py: -------------------------------------------------------------------------------- 1 | def naturals(): 2 | """A generator function that yields the infinite sequence of natural 3 | numbers, starting at 1. 4 | 5 | >>> m = naturals() 6 | >>> type(m) 7 | 8 | >>> [next(m) for _ in range(10)] 9 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 10 | """ 11 | i = 1 12 | while True: 13 | yield i 14 | i += 1 15 | 16 | 17 | def scale(it, multiplier): 18 | """Yield elements of the iterable it scaled by a number multiplier. 19 | 20 | >>> m = scale([1, 5, 2], 5) 21 | >>> type(m) 22 | 23 | >>> list(m) 24 | [5, 25, 10] 25 | 26 | >>> m = scale(naturals(), 2) 27 | >>> [next(m) for _ in range(5)] 28 | [2, 4, 6, 8, 10] 29 | """ 30 | # for i in it: 31 | # yield i * multiplier 32 | # OR 33 | yield from map(lambda x: multiplier * x, it) 34 | 35 | 36 | def hailstone(n): 37 | """ 38 | >>> for num in hailstone(10): 39 | ... print(num) 40 | ... 41 | 10 42 | 5 43 | 16 44 | 8 45 | 4 46 | 2 47 | 1 48 | """ 49 | if n == 1: 50 | yield 1 51 | else: 52 | yield n 53 | if n % 2 == 0: 54 | next = n // 2 55 | elif n % 2 == 1: 56 | next = n * 3 + 1 57 | yield from hailstone(next) 58 | -------------------------------------------------------------------------------- /lab/lab07/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab07/ok -------------------------------------------------------------------------------- /lab/lab07/tests/wwpd-car.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Car', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> from car import * 10 | >>> deneros_car = Car('Tesla', 'Model S') 11 | >>> deneros_car.model 12 | 'Model S' 13 | >>> deneros_car.gas = 10 14 | >>> deneros_car.drive() 15 | 'Tesla Model S goes vroom!' 16 | >>> deneros_car.drive() 17 | 'Cannot drive!' 18 | >>> deneros_car.fill_gas() 19 | 'Gas level: 20' 20 | >>> deneros_car.gas 21 | 20 22 | >>> Car.gas 23 | 30 24 | """, 25 | 'hidden': False, 26 | 'locked': False 27 | }, 28 | { 29 | 'code': r""" 30 | >>> from car import * 31 | >>> deneros_car = Car('Tesla', 'Model S') 32 | >>> deneros_car.wheels = 2 33 | >>> deneros_car.wheels 34 | 2 35 | >>> Car.num_wheels 36 | 4 37 | >>> deneros_car.drive() # Type Error if an error occurs and Nothing if nothing is displayed 38 | 'Cannot drive!' 39 | >>> Car.drive() # Type Error if an error occurs and Nothing if nothing is displayed 40 | Error 41 | >>> Car.drive(deneros_car) # Type Error if an error occurs and Nothing if nothing is displayed 42 | 'Cannot drive!' 43 | """, 44 | 'hidden': False, 45 | 'locked': False 46 | }, 47 | { 48 | 'code': r""" 49 | >>> from car import * 50 | >>> deneros_car = MonsterTruck('Monster', 'Batmobile') 51 | >>> deneros_car.drive() # Type Error if an error occurs and Nothing if nothing is displayed 52 | Vroom! This Monster Truck is huge! 53 | 'Monster Batmobile goes vroom!' 54 | >>> Car.drive(deneros_car) # Type Error if an error occurs and Nothing if nothing is displayed 55 | 'Monster Batmobile goes vroom!' 56 | >>> MonsterTruck.drive(deneros_car) # Type Error if an error occurs and Nothing if nothing is displayed 57 | Vroom! This Monster Truck is huge! 58 | 'Monster Batmobile goes vroom!' 59 | >>> Car.rev(deneros_car) # Type Error if an error occurs and Nothing if nothing is displayed 60 | Error 61 | """, 62 | 'hidden': False, 63 | 'locked': False 64 | } 65 | ], 66 | 'scored': False, 67 | 'type': 'wwpp' 68 | } 69 | ] 70 | } 71 | -------------------------------------------------------------------------------- /lab/lab08/lab08.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 8", 3 | "endpoint": "cal/cs61a/fa20/lab08", 4 | "src": [ 5 | "lab08.py" 6 | ], 7 | "tests": { 8 | "lab*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "link", 13 | "convert_link", 14 | "every_other", 15 | "cumulative_mul" 16 | ], 17 | "protocols": [ 18 | "restore", 19 | "file_contents", 20 | "unlock", 21 | "grading", 22 | "analytics", 23 | "backup" 24 | ] 25 | } -------------------------------------------------------------------------------- /lab/lab08/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab08/ok -------------------------------------------------------------------------------- /lab/lab08/tests/link.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Link', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> from lab09 import * 10 | >>> link = Link(1000) 11 | >>> link.first 12 | 1000 13 | >>> link.rest is Link.empty 14 | True 15 | >>> link = Link(1000, 2000) 16 | Error 17 | >>> link = Link(1000, Link()) 18 | Error 19 | """, 20 | 'hidden': False, 21 | 'locked': False 22 | }, 23 | { 24 | 'code': r""" 25 | >>> from lab09 import * 26 | >>> link = Link(1, Link(2, Link(3))) 27 | >>> link.first 28 | 1 29 | >>> link.rest.first 30 | 2 31 | >>> link.rest.rest.rest is Link.empty 32 | True 33 | >>> link.first = 9001 34 | >>> link.first 35 | 9001 36 | >>> link.rest = link.rest.rest 37 | >>> link.rest.first 38 | 3 39 | >>> link = Link(1) 40 | >>> link.rest = link 41 | >>> link.rest.rest.rest.rest.first 42 | 1 43 | >>> link = Link(2, Link(3, Link(4))) 44 | >>> link2 = Link(1, link) 45 | >>> link2.first 46 | 1 47 | >>> link2.rest.first 48 | 2 49 | """, 50 | 'hidden': False, 51 | 'locked': False 52 | }, 53 | { 54 | 'code': r""" 55 | >>> from lab09 import * 56 | >>> link = Link(5, Link(6, Link(7))) 57 | >>> link # Look at the __repr__ method of Link 58 | Link(5, Link(6, Link(7))) 59 | >>> print(link) # Look at the __str__ method of Link 60 | <5 6 7> 61 | """, 62 | 'hidden': False, 63 | 'locked': False 64 | } 65 | ], 66 | 'scored': False, 67 | 'type': 'wwpp' 68 | } 69 | ] 70 | } 71 | -------------------------------------------------------------------------------- /lab/lab09/lab09.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 9", 3 | "endpoint": "cal/cs61a/fa20/lab09", 4 | "src": [ 5 | "lab09.py" 6 | ], 7 | "tests": { 8 | "lab*.py": "doctest", 9 | "tests/*.py": "ok_test" 10 | }, 11 | "default_tests": [ 12 | "Tree.__contains__" 13 | ], 14 | "protocols": [ 15 | "restore", 16 | "file_contents", 17 | "unlock", 18 | "grading", 19 | "analytics", 20 | "backup" 21 | ] 22 | } -------------------------------------------------------------------------------- /lab/lab09/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab09/ok -------------------------------------------------------------------------------- /lab/lab10/lab10.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 10", 3 | "endpoint": "cal/cs61a/fa20/lab10", 4 | "src": [ 5 | "lab10.scm" 6 | ], 7 | "tests": { 8 | "tests/*.py": "ok_test" 9 | }, 10 | "default_tests": [ 11 | "combinations", 12 | "over_or_under", 13 | "make_adder", 14 | "composed" 15 | ], 16 | "protocols": [ 17 | "restore", 18 | "file_contents", 19 | "unlock", 20 | "grading", 21 | "analytics", 22 | "backup" 23 | ] 24 | } -------------------------------------------------------------------------------- /lab/lab10/lab10.scm: -------------------------------------------------------------------------------- 1 | (define (over-or-under num1 num2) 2 | (cond 3 | ((< num1 num2) -1) 4 | ((= num1 num2) 0) 5 | ((> num1 num2) 1) 6 | ) 7 | ) 8 | 9 | ;;; Tests 10 | (over-or-under 1 2) 11 | ; expect -1 12 | (over-or-under 2 1) 13 | ; expect 1 14 | (over-or-under 1 1) 15 | ; expect 0 16 | 17 | 18 | (define (make-adder num) 19 | (define (adder inc) 20 | (+ num inc)) 21 | adder 22 | ) 23 | 24 | ;;; Tests 25 | (define adder (make-adder 5)) 26 | (adder 8) 27 | ; expect 13 28 | 29 | 30 | (define (composed f g) 31 | (define (h x) 32 | (f (g x))) 33 | h 34 | ) 35 | 36 | 37 | (define lst 38 | (list (list 1) 2 (list 3 4) 5) 39 | ) 40 | 41 | 42 | (define (remove item lst) 43 | (filter-lst (lambda (x) (= x item)) lst) 44 | ) 45 | 46 | 47 | (define (filter-lst fn lst) 48 | (if (null? lst) 49 | nil ; should not use (nil) 50 | (if (fn (car lst)) 51 | (filter-lst fn (cdr lst)) 52 | (cons (car lst) (filter-lst fn (cdr lst))) 53 | ) 54 | ) 55 | ) 56 | 57 | ;;; Tests 58 | (remove 3 nil) 59 | ; expect () 60 | (remove 3 '(1 3 5)) 61 | ; expect (1 5) 62 | (remove 5 '(5 3 5 5 1 4 5 4)) 63 | ; expect (3 1 4 4) 64 | 65 | -------------------------------------------------------------------------------- /lab/lab10/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab10/ok -------------------------------------------------------------------------------- /lab/lab11/buffer.py: -------------------------------------------------------------------------------- 1 | class Buffer(object): 2 | """A Buffer provides a way of accessing a sequence one at a time. 3 | Its constructor takes a sequence, called the "source". 4 | The Buffer supplies elements from source one at a time through its pop_first() 5 | method. In addition, Buffer provides a current() method to look at the 6 | next item to be supplied, without moving past it. 7 | >>> buf = Buffer(['(', '+', 15, 12, ')']) 8 | >>> buf.pop_first() 9 | '(' 10 | >>> buf.pop_first() 11 | '+' 12 | >>> buf.current() 13 | 15 14 | >>> buf.pop_first() 15 | 15 16 | >>> buf.current() 17 | 12 18 | >>> buf.pop_first() 19 | 12 20 | >>> buf.pop_first() 21 | ')' 22 | >>> buf.pop_first() # returns None 23 | """ 24 | def __init__(self, source): 25 | self.index = 0 26 | self.source = source 27 | 28 | def pop_first(self): 29 | """Remove the next item from self and return it. If self has 30 | exhausted its source, returns None.""" 31 | current = self.current() 32 | self.index += 1 33 | return current 34 | 35 | def current(self): 36 | """Return the current element, or None if none exists.""" 37 | if self.index >= len(self.source): 38 | return None 39 | else: 40 | return self.source[self.index] 41 | 42 | def expect(self, expected): 43 | actual = self.pop_first() 44 | if expected != actual: 45 | raise SyntaxError("expected '{}' but got '{}'".format(expected, actual)) 46 | else: 47 | return actual 48 | 49 | def __str__(self): 50 | return str(self.source[self.index:]) 51 | 52 | -------------------------------------------------------------------------------- /lab/lab11/lab11.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 11", 3 | "endpoint": "cal/cs61a/fa20/lab11", 4 | "src": [ 5 | "expr.py", 6 | "repl.py" 7 | ], 8 | "tests": { 9 | "*.py": "doctest", 10 | "tests/*.py": "ok_test" 11 | }, 12 | "default_tests": [ 13 | "prologue_reader", 14 | "Name.eval", 15 | "CallExpr.eval" 16 | ], 17 | "protocols": [ 18 | "restore", 19 | "file_contents", 20 | "unlock", 21 | "grading", 22 | "analytics", 23 | "backup" 24 | ] 25 | } -------------------------------------------------------------------------------- /lab/lab11/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab11/ok -------------------------------------------------------------------------------- /lab/lab11/reader.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | from buffer import Buffer 4 | from expr import * 5 | 6 | SYMBOL_STARTS = set(string.ascii_lowercase + string.ascii_uppercase + '_') 7 | SYMBOL_INNERS = SYMBOL_STARTS | set(string.digits) 8 | NUMERAL = set(string.digits + '-.') 9 | WHITESPACE = set(' \t\n\r') 10 | DELIMITERS = set('(),:') 11 | 12 | def read(s): 13 | """Parse an expression from a string. If the string does not contain an 14 | expression, None is returned. If the string cannot be parsed, a SyntaxError 15 | is raised. 16 | 17 | >>> read('lambda f: f(0)') 18 | LambdaExpr(['f'], CallExpr(Name('f'), [Literal(0)])) 19 | >>> read('(lambda x: x)(5)') 20 | CallExpr(LambdaExpr(['x'], Name('x')), [Literal(5)]) 21 | >>> read('(lambda: 5)()') 22 | CallExpr(LambdaExpr([], Literal(5)), []) 23 | >>> read('lambda x y: 10') 24 | Traceback (most recent call last): 25 | ... 26 | SyntaxError: expected ':' but got 'y' 27 | >>> read(' ') # returns None 28 | """ 29 | src = Buffer(tokenize(s)) 30 | if src.current() is not None: 31 | return read_expr(src) 32 | 33 | ########### 34 | ## Lexer ## 35 | ########### 36 | def tokenize(s): 37 | """Splits the string s into tokens and returns a list of them. 38 | 39 | >>> tokenize('lambda f: f(0, 4.2)') 40 | ['lambda', 'f', ':', 'f', '(', 0, ',', 4.2, ')'] 41 | """ 42 | src = Buffer(s) 43 | tokens = [] 44 | while True: 45 | token = next_token(src) 46 | if token is None: 47 | return tokens 48 | tokens.append(token) 49 | 50 | def take(src, allowed_characters): 51 | result = '' 52 | while src.current() in allowed_characters: 53 | result += src.pop_first() 54 | return result 55 | 56 | def next_token(src): 57 | take(src, WHITESPACE) # skip whitespace 58 | c = src.current() 59 | if c is None: 60 | return None 61 | elif c in NUMERAL: 62 | literal = take(src, NUMERAL) 63 | try: 64 | return int(literal) 65 | except ValueError: 66 | try: 67 | return float(literal) 68 | except ValueError: 69 | raise SyntaxError("'{}' is not a numeral".format(literal)) 70 | elif c in SYMBOL_STARTS: 71 | return take(src, SYMBOL_INNERS) 72 | elif c in DELIMITERS: 73 | src.pop_first() 74 | return c 75 | else: 76 | raise SyntaxError("'{}' is not a token".format(c)) 77 | 78 | def is_literal(s): 79 | return isinstance(s, int) or isinstance(s, float) 80 | 81 | def is_name(s): 82 | return isinstance(s, str) and s not in DELIMITERS and s != 'lambda' 83 | 84 | ############ 85 | ## Parser ## 86 | ############ 87 | def read_expr(src): 88 | token = src.pop_first() 89 | if token is None: 90 | raise SyntaxError('Incomplete expression') 91 | elif is_literal(token): 92 | return read_call_expr(src, Literal(token)) 93 | elif is_name(token): 94 | return read_call_expr(src, Name(token)) 95 | elif token == 'lambda': 96 | params = read_comma_separated(src, read_param) 97 | src.expect(':') 98 | body = read_expr(src) 99 | return LambdaExpr(params, body) 100 | elif token == '(': 101 | inner_expr = read_expr(src) 102 | src.expect(')') 103 | return read_call_expr(src, inner_expr) 104 | else: 105 | raise SyntaxError("'{}' is not the start of an expression".format(token)) 106 | 107 | def read_comma_separated(src, reader): 108 | if src.current() in (':', ')'): 109 | return [] 110 | else: 111 | s = [reader(src)] 112 | while src.current() == ',': 113 | src.pop_first() 114 | s.append(reader(src)) 115 | return s 116 | 117 | def read_call_expr(src, operator): 118 | while src.current() == '(': 119 | src.pop_first() 120 | operands = read_comma_separated(src, read_expr) 121 | src.expect(')') 122 | operator = CallExpr(operator, operands) 123 | return operator 124 | 125 | def read_param(src): 126 | token = src.pop_first() 127 | if is_name(token): 128 | return token 129 | else: 130 | raise SyntaxError("Expected parameter name but got '{}'".format(token)) 131 | 132 | -------------------------------------------------------------------------------- /lab/lab11/repl.py: -------------------------------------------------------------------------------- 1 | try: 2 | import readline # history and arrow keys for CLI 3 | except ImportError: 4 | pass # but not everyone has it 5 | import sys 6 | 7 | from reader import read 8 | from expr import global_env 9 | 10 | # program start 11 | if __name__ == '__main__': 12 | """Run a read-eval-print loop. 13 | `python3 repl.py` to start an interactive REPL. 14 | `python3 repl.py --read` to interactively read expressions and 15 | print their Python representations. 16 | """ 17 | read_only = len(sys.argv) == 2 and sys.argv[1] == '--read' 18 | 19 | while True: 20 | try: 21 | # `input` prints the prompt, waits, and returns the user's input. 22 | user_input = input('> ') 23 | expr = read(user_input) 24 | if expr is not None: 25 | if read_only: 26 | print(repr(expr)) 27 | else: 28 | print(expr.eval(global_env)) 29 | except (SyntaxError, NameError, TypeError, ZeroDivisionError) as err: 30 | print(type(err).__name__ + ':', err) 31 | except (KeyboardInterrupt, EOFError): # Ctrl-C, Ctrl-D 32 | print() # blank line 33 | break # exit while loop (and end program) 34 | -------------------------------------------------------------------------------- /lab/lab11/scheme: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab11/scheme -------------------------------------------------------------------------------- /lab/lab11/utils.py: -------------------------------------------------------------------------------- 1 | def comma_separated(xs): 2 | """Convert each value in the sequence xs to a string, and separate them 3 | with commas. 4 | 5 | >>> comma_separated(['spam', 5, False]) 6 | 'spam, 5, False' 7 | >>> comma_separated([5]) 8 | '5' 9 | >>> comma_separated([]) 10 | '' 11 | """ 12 | return ', '.join([str(x) for x in xs]) 13 | 14 | -------------------------------------------------------------------------------- /lab/lab12/lab12.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 12", 3 | "endpoint": "cal/cs61a/fa20/lab12", 4 | "src": [ 5 | "lab12.sql" 6 | ], 7 | "tests": { 8 | "tests/*.py": "ok_test" 9 | }, 10 | "default_tests": [ 11 | "bluedog", 12 | "matchmaker", 13 | "sevens", 14 | "smallest-int" 15 | ], 16 | "protocols": [ 17 | "restore", 18 | "file_contents", 19 | "unlock", 20 | "grading", 21 | "analytics", 22 | "backup" 23 | ] 24 | } -------------------------------------------------------------------------------- /lab/lab12/lab12.sql: -------------------------------------------------------------------------------- 1 | .read data.sql 2 | 3 | 4 | CREATE TABLE bluedog AS 5 | SELECT color, pet FROM students WHERE color='blue'and pet='dog'; 6 | 7 | CREATE TABLE bluedog_songs AS 8 | SELECT color, pet, song FROM students WHERE color='blue'and pet='dog'; 9 | 10 | 11 | CREATE TABLE smallest_int AS 12 | SELECT time, smallest 13 | FROM students 14 | WHERE smallest>2 ORDER BY smallest LIMIT 20; 15 | 16 | 17 | CREATE TABLE matchmaker AS 18 | SELECT s1.pet, s1.song, s1.color, s2.color 19 | FROM students AS s1, students AS s2 20 | WHERE s1.time SELECT * FROM bluedog; 10 | blue|dog 11 | blue|dog 12 | blue|dog 13 | blue|dog 14 | blue|dog 15 | blue|dog 16 | blue|dog 17 | blue|dog 18 | blue|dog 19 | blue|dog 20 | blue|dog 21 | blue|dog 22 | blue|dog 23 | blue|dog 24 | blue|dog 25 | blue|dog 26 | blue|dog 27 | blue|dog 28 | blue|dog 29 | blue|dog 30 | blue|dog 31 | blue|dog 32 | blue|dog 33 | blue|dog 34 | blue|dog 35 | blue|dog 36 | sqlite> SELECT * FROM bluedog_songs; 37 | blue|dog|Smells like Teen Spirit 38 | blue|dog|The Middle 39 | blue|dog|Clair De Lune 40 | blue|dog|Smells like Teen Spirit 41 | blue|dog|Everytime We Touch 42 | blue|dog|Dancing Queen 43 | blue|dog|Clair De Lune 44 | blue|dog|Clair De Lune 45 | blue|dog|The Middle 46 | blue|dog|Down With The Sickness 47 | blue|dog|thank u, next 48 | blue|dog|All I want for Christmas is you 49 | blue|dog|Everytime We Touch 50 | blue|dog|Clair De Lune 51 | blue|dog|Everytime We Touch 52 | blue|dog|thank u, next 53 | blue|dog|All I want for Christmas is you 54 | blue|dog|Smells like Teen Spirit 55 | blue|dog|The Middle 56 | blue|dog|Clair De Lune 57 | blue|dog|Dancing Queen 58 | blue|dog|All I want for Christmas is you 59 | blue|dog|Dancing Queen 60 | blue|dog|Clair De Lune 61 | blue|dog|Dancing Queen 62 | blue|dog|Dancing Queen 63 | """, 64 | 'hidden': False, 65 | 'locked': False 66 | } 67 | ], 68 | 'ordered': False, 69 | 'scored': True, 70 | 'setup': r""" 71 | sqlite> .read lab12.sql 72 | """, 73 | 'teardown': '', 74 | 'type': 'sqlite' 75 | } 76 | ] 77 | } 78 | -------------------------------------------------------------------------------- /lab/lab12/tests/matchmaker.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'matchmaker', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | sqlite> SELECT * FROM matchmaker LIMIT 10; 10 | dog|Smells like Teen Spirit|blue|yellow 11 | dog|Smells like Teen Spirit|blue|blue 12 | dog|Smells like Teen Spirit|blue|yellow 13 | dog|Smells like Teen Spirit|blue|blue 14 | dog|Smells like Teen Spirit|blue|black 15 | dog|All I want for Christmas is you|maroon|purple 16 | dog|All I want for Christmas is you|maroon|pink 17 | dog|All I want for Christmas is you|maroon|pink 18 | dog|All I want for Christmas is you|maroon|green 19 | dog|All I want for Christmas is you|maroon|red 20 | """, 21 | 'hidden': False, 22 | 'locked': False 23 | } 24 | ], 25 | 'ordered': False, 26 | 'scored': True, 27 | 'setup': r""" 28 | sqlite> .read lab12.sql 29 | """, 30 | 'teardown': '', 31 | 'type': 'sqlite' 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /lab/lab12/tests/sevens.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'sevens', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | sqlite> SELECT * FROM sevens; 10 | 7 11 | 7 12 | You're not the boss of me! 13 | 7 14 | the number 7 below. 15 | 7 16 | Choose this option instead 17 | You're not the boss of me! 18 | the number 7 below. 19 | You're not the boss of me! 20 | the number 7 below. 21 | 7 22 | 7 23 | You're not the boss of me! 24 | Choose this option instead 25 | 7 26 | the number 7 below. 27 | You're not the boss of me! 28 | 7 29 | You're not the boss of me! 30 | the number 7 below. 31 | 7 32 | the number 7 below. 33 | the number 7 below. 34 | 7 35 | """, 36 | 'hidden': False, 37 | 'locked': False 38 | } 39 | ], 40 | 'ordered': False, 41 | 'scored': True, 42 | 'setup': r""" 43 | sqlite> .read lab12.sql 44 | """, 45 | 'teardown': '', 46 | 'type': 'sqlite' 47 | } 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /lab/lab12/tests/smallest-int.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'smallest-int', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | sqlite> SELECT * FROM smallest_int; 10 | 11/13/2020 10:06:33|3 11 | 11/13/2020 12:57:26|3 12 | 11/13/2020 12:58:12|3 13 | 11/13/2020 14:08:32|3 14 | 11/13/2020 1:48:13|3 15 | 11/13/2020 1:57:30|3 16 | 11/13/2020 8:45:37|3 17 | 11/13/2020 9:14:41|3 18 | 11/13/2020 9:56:23|3 19 | 11/13/2020 12:14:58|4 20 | 11/13/2020 12:33:03|4 21 | 11/13/2020 2:00:47|4 22 | 11/13/2020 2:09:24|4 23 | 11/13/2020 2:32:03|4 24 | 11/13/2020 8:37:44|4 25 | 11/13/2020 11:32:57|5 26 | 11/13/2020 12:50:42|5 27 | 11/13/2020 1:46:30|5 28 | 11/13/2020 1:46:37|5 29 | 11/13/2020 2:05:11|5 30 | """, 31 | 'hidden': False, 32 | 'locked': False 33 | } 34 | ], 35 | 'ordered': False, 36 | 'scored': True, 37 | 'setup': r""" 38 | sqlite> .read lab12.sql 39 | """, 40 | 'teardown': '', 41 | 'type': 'sqlite' 42 | } 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /lab/lab13/lab13.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 13", 3 | "endpoint": "cal/cs61a/fa20/lab13", 4 | "src": [ 5 | "lab13.sql" 6 | ], 7 | "tests": { 8 | "tests/*.py": "ok_test" 9 | }, 10 | "default_tests": [ 11 | "default" 12 | ], 13 | "protocols": [ 14 | "restore", 15 | "file_contents", 16 | "unlock", 17 | "grading", 18 | "analytics", 19 | "backup" 20 | ] 21 | } -------------------------------------------------------------------------------- /lab/lab13/lab13.sql: -------------------------------------------------------------------------------- 1 | .read data.sql 2 | 3 | 4 | CREATE TABLE average_prices AS 5 | SELECT category, avg(MSRP) as average_price 6 | FROM products 7 | GROUP BY category; 8 | 9 | 10 | CREATE TABLE lowest_prices AS 11 | SELECT store, item, min(price) 12 | FROM inventory 13 | GROUP BY item; 14 | 15 | 16 | CREATE TABLE best_deals AS 17 | SELECT name, min(MSRP/rating) as Cost_performance 18 | FROM products 19 | GROUP BY category; 20 | 21 | CREATE TABLE shopping_list AS 22 | SELECT b.name, l.store 23 | FROM best_deals as b, lowest_prices as l 24 | WHERE b.name = l.item; 25 | 26 | 27 | CREATE TABLE total_bandwidth AS 28 | SELECT sum(Mbs) 29 | FROM shopping_list, stores 30 | WHERE shopping_list.store = stores.store; 31 | -------------------------------------------------------------------------------- /lab/lab13/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab13/ok -------------------------------------------------------------------------------- /lab/lab14/lab14.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lab 14", 3 | "endpoint": "cal/cs61a/fa20/lab14", 4 | "src": [ 5 | "lab14.py", 6 | "lab14.scm" 7 | ], 8 | "tests": { 9 | "lab*.py": "doctest", 10 | "tests/*.py": "ok_test" 11 | }, 12 | "default_tests": [ 13 | "prune_min", 14 | "split-at", 15 | "compose-all", 16 | "num_splits" 17 | ], 18 | "protocols": [ 19 | "restore", 20 | "file_contents", 21 | "unlock", 22 | "grading", 23 | "analytics", 24 | "backup" 25 | ] 26 | } -------------------------------------------------------------------------------- /lab/lab14/lab14.scm: -------------------------------------------------------------------------------- 1 | (define (split-at lst n) 2 | (if (> n (length lst)) 3 | (list lst) 4 | (if (= n 0) 5 | (cons nil lst) 6 | (cons 7 | (append (car (split-at lst (- n 1))) (list (car (cdr (split-at lst (- n 1)))))) 8 | (cdr (cdr (split-at lst (- n 1)))) 9 | ) 10 | ) 11 | ) 12 | ) 13 | 14 | 15 | (define (compose-all funcs) 16 | (define (helper x) 17 | (if (null? funcs) 18 | x 19 | ((compose-all (cdr funcs)) ((car funcs) x)) 20 | ) 21 | ) 22 | helper 23 | ) 24 | 25 | -------------------------------------------------------------------------------- /lab/lab14/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/lab/lab14/ok -------------------------------------------------------------------------------- /projects/ants/ants_plans.py: -------------------------------------------------------------------------------- 1 | 2 | from ants import * 3 | 4 | def make_test_assault_plan(): 5 | return AssaultPlan().add_wave(Bee, 3, 2, 1).add_wave(Bee, 3, 3, 1) 6 | 7 | def make_easy_assault_plan(): 8 | plan = AssaultPlan() 9 | for time in range(3, 16, 2): 10 | plan.add_wave(Bee, 3, time, 1) 11 | plan.add_wave(Wasp, 3, 4, 1) 12 | plan.add_wave(NinjaBee, 3, 8, 1) 13 | plan.add_wave(Hornet, 3, 12, 1) 14 | plan.add_wave(Boss, 15, 16, 1) 15 | return plan 16 | 17 | def make_normal_assault_plan(): 18 | plan = AssaultPlan() 19 | for time in range(3, 16, 2): 20 | plan.add_wave(Bee, 3, time, 2) 21 | plan.add_wave(Wasp, 3, 4, 1) 22 | plan.add_wave(NinjaBee, 3, 8, 1) 23 | plan.add_wave(Hornet, 3, 12, 1) 24 | plan.add_wave(Wasp, 3, 16, 1) 25 | 26 | #Boss Stage 27 | for time in range(21, 30, 2): 28 | plan.add_wave(Bee, 3, time, 2) 29 | plan.add_wave(Wasp, 3, 22, 2) 30 | plan.add_wave(Hornet, 3, 24, 2) 31 | plan.add_wave(NinjaBee, 3, 26, 2) 32 | plan.add_wave(Hornet, 3, 28, 2) 33 | plan.add_wave(Boss, 20, 30, 1) 34 | return plan 35 | 36 | def make_hard_assault_plan(): 37 | plan = AssaultPlan() 38 | for time in range(3, 16, 2): 39 | plan.add_wave(Bee, 4, time, 2) 40 | plan.add_wave(Hornet, 4, 4, 2) 41 | plan.add_wave(Wasp, 4, 8, 2) 42 | plan.add_wave(NinjaBee, 4, 12, 2) 43 | plan.add_wave(Wasp, 4, 16, 2) 44 | 45 | #Boss Stage 46 | for time in range(21, 30, 2): 47 | plan.add_wave(Bee, 4, time, 3) 48 | plan.add_wave(Wasp, 4, 22, 2) 49 | plan.add_wave(Hornet, 4, 24, 2) 50 | plan.add_wave(NinjaBee, 4, 26, 2) 51 | plan.add_wave(Hornet, 4, 28, 2) 52 | plan.add_wave(Boss, 30, 30, 1) 53 | return plan 54 | 55 | def make_extra_hard_assault_plan(): 56 | plan = AssaultPlan() 57 | plan.add_wave(Hornet, 5, 2, 2) 58 | for time in range(3, 16, 2): 59 | plan.add_wave(Bee, 5, time, 2) 60 | plan.add_wave(Hornet, 5, 4, 2) 61 | plan.add_wave(Wasp, 5, 8, 2) 62 | plan.add_wave(NinjaBee, 5, 12, 2) 63 | plan.add_wave(Wasp, 5, 16, 2) 64 | 65 | #Boss Stage 66 | for time in range(21, 30, 2): 67 | plan.add_wave(Bee, 5, time, 3) 68 | plan.add_wave(Wasp, 5, 22, 2) 69 | plan.add_wave(Hornet, 5, 24, 2) 70 | plan.add_wave(NinjaBee, 5, 26, 2) 71 | plan.add_wave(Hornet, 5, 28, 2) 72 | plan.add_wave(Boss, 30, 30, 2) 73 | return plan -------------------------------------------------------------------------------- /projects/ants/ants_strategies.py: -------------------------------------------------------------------------------- 1 | from ants import * 2 | from ants_plans import * 3 | 4 | def start_with_strategy(args, strategy): 5 | """Reads command-line arguments and starts a game with those options.""" 6 | import argparse 7 | parser = argparse.ArgumentParser(description="Play Ants vs. SomeBees") 8 | parser.add_argument('-d', type=str, metavar='DIFFICULTY', 9 | help='sets difficulty of game (test/easy/medium/hard/extra-hard)') 10 | parser.add_argument('-w', '--water', action='store_true', 11 | help='loads a full layout with water') 12 | parser.add_argument('--food', type=int, 13 | help='number of food to start with when testing', default=2) 14 | args = parser.parse_args() 15 | 16 | assault_plan = make_normal_assault_plan() 17 | layout = dry_layout 18 | tunnel_length = 10 19 | num_tunnels = 3 20 | food = args.food 21 | 22 | if args.water: 23 | layout = wet_layout 24 | if args.d in ['t', 'test']: 25 | assault_plan = make_test_assault_plan() 26 | num_tunnels = 1 27 | elif args.d in ['e', 'easy']: 28 | assault_plan = make_easy_assault_plan() 29 | num_tunnels = 2 30 | elif args.d in ['n', 'normal']: 31 | assault_plan = make_normal_assault_plan() 32 | num_tunnels = 3 33 | elif args.d in ['h', 'hard']: 34 | assault_plan = make_hard_assault_plan() 35 | num_tunnels = 4 36 | elif args.d in ['i', 'extra-hard']: 37 | assault_plan = make_extra_hard_assault_plan() 38 | num_tunnels = 4 39 | 40 | beehive = Hive(assault_plan) 41 | dimensions = (num_tunnels, tunnel_length) 42 | return GameState(strategy, beehive, ant_types(), layout, dimensions, food).simulate() -------------------------------------------------------------------------------- /projects/ants/ants_text.py: -------------------------------------------------------------------------------- 1 | 2 | from utils import * 3 | from ants import * 4 | from ants_strategies import start_with_strategy 5 | 6 | @main 7 | def run(*args): 8 | Insect.reduce_armor = class_method_wrapper(Insect.reduce_armor, 9 | pre=print_expired_insects) 10 | start_with_strategy(args, interactive_strategy) -------------------------------------------------------------------------------- /projects/ants/assets/app.css: -------------------------------------------------------------------------------- 1 | @import url("https://fonts.googleapis.com/css?family=Montserrat&display=swap"); 2 | 3 | body { 4 | background-image: url('swirl_pattern.png'); 5 | font-family: "Arial"; 6 | } 7 | 8 | .outside-container { 9 | width: 1280px; 10 | margin: auto; 11 | } 12 | .hero-header { 13 | /* width: 100%; */ 14 | height: 780px; 15 | background-image: url('splash.png'); 16 | background-size: cover; 17 | } 18 | .header-text { 19 | color: #FFFFFF; 20 | text-shadow: 4px 4px 2px rgba(76, 74, 74, 1); 21 | } 22 | .logo { 23 | width: 60px; 24 | height: 60px; 25 | float: left; 26 | } 27 | .game-wrapper { 28 | color: #FFFFFF; 29 | /* width: 100%; */ 30 | margin-top: 0px; 31 | margin-bottom: -10px; 32 | min-height: 780px; 33 | background-image:url('main-background.png'); 34 | background-size: cover; 35 | } 36 | .game-wrapper h1 { 37 | color: #FFFFFF; 38 | } 39 | .game-wrapper > .container { 40 | margin-top: 0px; 41 | } 42 | 43 | .ants-table { 44 | background-color: #FFFFFF; 45 | } 46 | .ant-row { 47 | background-color: #FFFFFF; 48 | color: #000000; 49 | cursor: pointer; 50 | } 51 | .ant-img { 52 | height: 64px; 53 | width: 64px; 54 | } 55 | 56 | .label { 57 | background-color: #FFC300; 58 | color: white; 59 | border: none; 60 | box-shadow: none; 61 | font-size: 17px; 62 | font-weight: 500; 63 | -webkit-border-radius: 4px; 64 | border-radius: 5px; 65 | padding: 10px 10px; 66 | margin: 0 5px 0 0; 67 | } 68 | 69 | .button { 70 | background-color: #FFEECC; 71 | color: black; 72 | border: none; 73 | box-shadow: none; 74 | font-size: 17px; 75 | font-weight: 500; 76 | -webkit-border-radius: 4px; 77 | border-radius: 5px; 78 | padding: 10px 32px; 79 | margin: 26px 5px 0 5px; 80 | cursor: pointer; 81 | } 82 | .button:focus { 83 | outline: none; 84 | box-shadow: 0 0 2px rgba(128, 179, 235, 0.5), inset 0 0 0 1px rgba(0, 0, 0, 0.05); } 85 | .button:hover { 86 | background-color: #a1d9f2; } 87 | .button:active { 88 | background-color: #81ccee; } 89 | .button.cancel { 90 | background-color: #D0D0D0; } 91 | .button.cancel:hover { 92 | background-color: #c8c8c8; } 93 | .button.cancel:active { 94 | background-color: #b6b6b6; } 95 | .button.cancel:focus { 96 | box-shadow: rgba(197, 205, 211, 0.8) 0px 0px 2px, rgba(0, 0, 0, 0.0470588) 0px 0px 0px 1px inset !important; } 97 | .button::-moz-focus-inner { 98 | border: 0; } 99 | 100 | .exit-btn { 101 | background-color: #FF5733; 102 | color: white; 103 | margin: 0 10px 0 0; 104 | padding: 10px 10px; 105 | } 106 | .fork-frame { 107 | position: absolute; 108 | right: 0px; 109 | top: 20px; 110 | } 111 | .ant-row-divider { 112 | margin-top: 1px; 113 | margin-bottom: 1px; 114 | } 115 | .ant-cost { 116 | width: 64px; 117 | margin: 0 auto; 118 | } 119 | .ant-inactive { 120 | opacity: 0.2 121 | } 122 | .ant-selected { 123 | background-color: #f0ad4e; 124 | } 125 | .tunnel-div { 126 | height: 160px; 127 | width: 80px; 128 | } 129 | .tunnel-img-container { 130 | margin-top: 40px; 131 | margin-left: 10px; 132 | position: absolute; 133 | } 134 | .tunnel-goc-div { 135 | height: 80px; 136 | width: 80px; 137 | } 138 | .places-table { 139 | float: none; 140 | margin: 0 auto; 141 | margin-top: 40px; 142 | margin-bottom: 70px; 143 | } 144 | .beehive-td, .places-td { 145 | cursor: pointer; 146 | border: 1px solid #4a474a; 147 | } 148 | .bee-img { 149 | width: 64px; 150 | height: 64px; 151 | } 152 | .active-ant { 153 | position: absolute; 154 | width: 64px; 155 | height: 64px; 156 | } 157 | 158 | .contained-ant{ 159 | position: absolute; 160 | width: 64px; 161 | height: 64px; 162 | } -------------------------------------------------------------------------------- /projects/ants/assets/colony-drawing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/colony-drawing.png -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_bodyguard.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_bodyguard.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_fire.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_fire.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_harvester.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_harvester.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_hungry.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_hungry.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_laser.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_laser.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_longthrower.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_longthrower.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_ninja.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_ninja.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_queen.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_queen.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_scary.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_scary.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_scuba.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_scuba.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_shortthrower.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_shortthrower.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_slow.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_slow.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_tank.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_tank.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_thrower.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_thrower.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/ant_wall.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/ant_wall.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/bee.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/bee.gif -------------------------------------------------------------------------------- /projects/ants/assets/insects/remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/insects/remove.png -------------------------------------------------------------------------------- /projects/ants/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/logo.png -------------------------------------------------------------------------------- /projects/ants/assets/main-background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/main-background.png -------------------------------------------------------------------------------- /projects/ants/assets/new-ants-gui.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/new-ants-gui.png -------------------------------------------------------------------------------- /projects/ants/assets/splash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/splash.png -------------------------------------------------------------------------------- /projects/ants/assets/submitted.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/submitted.png -------------------------------------------------------------------------------- /projects/ants/assets/swirl_pattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/swirl_pattern.png -------------------------------------------------------------------------------- /projects/ants/assets/tiles/ground/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/tiles/ground/1.png -------------------------------------------------------------------------------- /projects/ants/assets/tiles/ground/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/tiles/ground/2.png -------------------------------------------------------------------------------- /projects/ants/assets/tiles/ground/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/tiles/ground/3.png -------------------------------------------------------------------------------- /projects/ants/assets/tiles/ground/water.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/tiles/ground/water.png -------------------------------------------------------------------------------- /projects/ants/assets/tiles/sky/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/tiles/sky/1.png -------------------------------------------------------------------------------- /projects/ants/assets/tiles/sky/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/tiles/sky/2.png -------------------------------------------------------------------------------- /projects/ants/assets/tiles/sky/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/assets/tiles/sky/3.png -------------------------------------------------------------------------------- /projects/ants/img/ant_bodyguard.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_bodyguard.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_fire.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_fire.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_harvester.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_harvester.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_hungry.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_hungry.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_laser.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_laser.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_longthrower.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_longthrower.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_ninja.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_ninja.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_queen.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_queen.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_scary.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_scary.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_scuba.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_scuba.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_shortthrower.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_shortthrower.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_slow.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_slow.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_stun.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_stun.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_tank.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_tank.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_thrower.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_thrower.gif -------------------------------------------------------------------------------- /projects/ants/img/ant_wall.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ant_wall.gif -------------------------------------------------------------------------------- /projects/ants/img/ants_vs_bees.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ants_vs_bees.png -------------------------------------------------------------------------------- /projects/ants/img/bee.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/bee.gif -------------------------------------------------------------------------------- /projects/ants/img/boss.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/boss.gif -------------------------------------------------------------------------------- /projects/ants/img/gui_explanation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/gui_explanation.png -------------------------------------------------------------------------------- /projects/ants/img/hornet.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/hornet.gif -------------------------------------------------------------------------------- /projects/ants/img/new_ants_gui.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/new_ants_gui.png -------------------------------------------------------------------------------- /projects/ants/img/ninjabee.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/ninjabee.gif -------------------------------------------------------------------------------- /projects/ants/img/remover.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/remover.gif -------------------------------------------------------------------------------- /projects/ants/img/tunnel.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/tunnel.gif -------------------------------------------------------------------------------- /projects/ants/img/wasp.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/img/wasp.gif -------------------------------------------------------------------------------- /projects/ants/ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/ants/ok -------------------------------------------------------------------------------- /projects/ants/proj03.ok: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Project 3: Ants Vs. SomeBees", 3 | "endpoint": "cal/cs61a/fa20/proj03", 4 | "src": [ 5 | "ants.py" 6 | ], 7 | "tests": { 8 | "tests/0[0-9].py": "ok_test", 9 | "tests/1[0-3].py": "ok_test", 10 | "tests/EC.py": "ok_test", 11 | "tests/optional[1-5].py": "ok_test" 12 | }, 13 | "default_tests": [ 14 | "00", 15 | "01", 16 | "02", 17 | "03", 18 | "04", 19 | "05", 20 | "06", 21 | "07", 22 | "08", 23 | "09", 24 | "EC" 25 | ], 26 | "protocols": [ 27 | "restore", 28 | "file_contents", 29 | "unlock", 30 | "grading", 31 | "analytics", 32 | "collaborate", 33 | "backup" 34 | ] 35 | } -------------------------------------------------------------------------------- /projects/ants/state.py: -------------------------------------------------------------------------------- 1 | class State: 2 | """A State holds a current game state and all of its attributes""" 3 | 4 | def __init__(self): 5 | """Create a new gamestate""" 6 | self.gs = {} 7 | 8 | 9 | def getState(self, key=None): 10 | if key: 11 | return self.gs[key] 12 | return self.gs 13 | 14 | def updateState(self, key, val): 15 | self.gs[key] = val 16 | 17 | 18 | -------------------------------------------------------------------------------- /projects/ants/tests/01.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Problem 1', 3 | 'points': 1, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'answer': "Placing an ant into the colony will decrease the colony's total available food by that ant's food_cost", 9 | 'choices': [ 10 | r""" 11 | Placing an ant into the colony will decrease the colony's total 12 | available food by that ant's food_cost 13 | """, 14 | r""" 15 | Each turn, each Ant in the colony eats food_cost food from the 16 | colony's total available food 17 | """, 18 | r""" 19 | Each turn, each Ant in the colony adds food_cost food to the 20 | colony's total available food 21 | """ 22 | ], 23 | 'hidden': False, 24 | 'locked': False, 25 | 'question': 'What is the purpose of the food_cost attribute?' 26 | }, 27 | { 28 | 'answer': 'class, all Ants of the same subclass cost the same to deploy', 29 | 'choices': [ 30 | 'class, all Ants of the same subclass cost the same to deploy', 31 | 'class, all Ants cost the same to deploy no matter what type of Ant it is', 32 | 'instance, the food_cost of an Ant depends on the location it is placed', 33 | 'instance, the food_cost of an Ant is randomized upon initialization' 34 | ], 35 | 'hidden': False, 36 | 'locked': False, 37 | 'question': 'What type of attribute is food_cost?' 38 | } 39 | ], 40 | 'scored': True, 41 | 'type': 'concept' 42 | }, 43 | { 44 | 'cases': [ 45 | { 46 | 'code': r""" 47 | >>> Ant.food_cost 48 | 0 49 | >>> HarvesterAnt.food_cost 50 | 2 51 | >>> ThrowerAnt.food_cost 52 | 3 53 | """, 54 | 'hidden': False, 55 | 'locked': False 56 | }, 57 | { 58 | 'code': r""" 59 | >>> # Testing HarvesterAnt action 60 | >>> # Note that initializing an Ant here doesn't cost food, only 61 | >>> # deploying an Ant in the game simulation does 62 | >>> # 63 | >>> # Create a test layout where the colony is a single row with 9 tiles 64 | >>> beehive = Hive(make_test_assault_plan()) 65 | >>> gamestate = GameState(None, beehive, ant_types(), dry_layout, (1, 9)) 66 | >>> # 67 | >>> gamestate.food = 4 68 | >>> harvester = HarvesterAnt() 69 | >>> harvester.action(gamestate) 70 | >>> gamestate.food 71 | 5 72 | >>> harvester.action(gamestate) 73 | >>> gamestate.food 74 | 6 75 | """, 76 | 'hidden': False, 77 | 'locked': False 78 | } 79 | ], 80 | 'scored': True, 81 | 'setup': r""" 82 | >>> from ants import * 83 | >>> from ants_plans import * 84 | """, 85 | 'teardown': '', 86 | 'type': 'doctest' 87 | }, 88 | { 89 | 'cases': [ 90 | { 91 | 'code': r""" 92 | >>> from ants import * 93 | >>> HarvesterAnt.implemented 94 | True 95 | """, 96 | 'hidden': False, 97 | 'locked': False 98 | } 99 | ], 100 | 'scored': True, 101 | 'setup': '', 102 | 'teardown': '', 103 | 'type': 'doctest' 104 | } 105 | ] 106 | } 107 | -------------------------------------------------------------------------------- /projects/ants/tests/02.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Problem 2', 3 | 'points': 3, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'answer': 'A single tile that an Ant can be placed on and that connects to other Places', 9 | 'choices': [ 10 | r""" 11 | A single tile that an Ant can be placed on and that connects to 12 | other Places 13 | """, 14 | 'The entire space where the game takes place', 15 | 'The tunnel that bees travel through', 16 | 'Where the bees start out in the game' 17 | ], 18 | 'hidden': False, 19 | 'locked': False, 20 | 'question': 'What does a Place represent in the game?' 21 | }, 22 | { 23 | 'answer': 'When q is constructed', 24 | 'choices': [ 25 | 'When p is constructed', 26 | 'When q is constructed', 27 | 'Never, it is always set to None' 28 | ], 29 | 'hidden': False, 30 | 'locked': False, 31 | 'question': 'p is a Place whose entrance is q and exit is r (q and r are not None). When is p.entrance first set to a non-None value?' 32 | }, 33 | { 34 | 'answer': 'When p is constructed', 35 | 'choices': [ 36 | 'When p is constructed', 37 | 'When q is constructed', 38 | 'Never, it is always set to None' 39 | ], 40 | 'hidden': False, 41 | 'locked': False, 42 | 'question': 'p is a Place whose entrance is q and exit is r (q and r are not None). When is p.exit first set to a non-None value?' 43 | } 44 | ], 45 | 'scored': True, 46 | 'type': 'concept' 47 | }, 48 | { 49 | 'cases': [ 50 | { 51 | 'code': r""" 52 | >>> # Simple test for Place 53 | >>> place0 = Place('place_0') 54 | >>> print(place0.exit) 55 | None 56 | >>> print(place0.entrance) 57 | None 58 | >>> place1 = Place('place_1', place0) 59 | >>> place1.exit is place0 60 | True 61 | >>> place0.entrance is place1 62 | True 63 | """, 64 | 'hidden': False, 65 | 'locked': False 66 | }, 67 | { 68 | 'code': r""" 69 | >>> # Testing if entrances are properly initialized 70 | >>> tunnel_len = 9 71 | >>> len(gamestate.bee_entrances) 72 | 1 73 | >>> tile_1 = gamestate.bee_entrances[0] 74 | >>> tile_2 = tile_1.exit 75 | >>> tile_3 = tile_2.exit 76 | >>> tile_1.entrance is gamestate.beehive 77 | True 78 | >>> tile_1.exit is tile_2 79 | True 80 | >>> tile_2.entrance is tile_1 81 | True 82 | >>> tile_2.exit is tile_3 83 | True 84 | >>> tile_3.entrance is tile_2 85 | True 86 | >>> tile_3.exit is gamestate.base 87 | True 88 | """, 89 | 'hidden': False, 90 | 'locked': False 91 | } 92 | ], 93 | 'scored': True, 94 | 'setup': r""" 95 | >>> from ants import * 96 | >>> from ants_plans import * 97 | >>> # 98 | >>> # Create a test layout where the gamestate is a single row with 3 tiles 99 | >>> beehive, layout = Hive(make_test_assault_plan()), dry_layout 100 | >>> dimensions = (1, 3) 101 | >>> gamestate = GameState(None, beehive, ant_types(), layout, dimensions) 102 | >>> # 103 | """, 104 | 'teardown': '', 105 | 'type': 'doctest' 106 | } 107 | ] 108 | } 109 | -------------------------------------------------------------------------------- /projects/ants/tests/optional5.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Problem Optional 5', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> laser = LaserAnt() 10 | >>> ant = HarvesterAnt(2) 11 | >>> bee1 = Bee(2) 12 | >>> bee2 = Bee(2) 13 | >>> bee3 = Bee(2) 14 | >>> bee4 = Bee(2) 15 | >>> gamestate.places["tunnel_0_0"].add_insect(laser) 16 | >>> gamestate.places["tunnel_0_0"].add_insect(bee4) 17 | >>> gamestate.places["tunnel_0_3"].add_insect(bee1) 18 | >>> gamestate.places["tunnel_0_3"].add_insect(bee2) 19 | >>> gamestate.places["tunnel_0_4"].add_insect(ant) 20 | >>> gamestate.places["tunnel_0_5"].add_insect(bee3) 21 | >>> laser.action(gamestate) 22 | >>> round(bee4.armor, 2) 23 | 0.0 24 | >>> round(bee1.armor, 2) 25 | 0.65 26 | >>> round(bee2.armor, 2) 27 | 0.7 28 | >>> round(ant.armor, 2) 29 | 0.95 30 | >>> round(bee3.armor, 2) 31 | 1.2 32 | """, 33 | 'hidden': False, 34 | 'locked': False 35 | } 36 | ], 37 | 'scored': True, 38 | 'setup': r""" 39 | >>> from ants import * 40 | >>> beehive, layout = Hive(AssaultPlan()), dry_layout 41 | >>> dimensions = (1, 9) 42 | >>> gamestate = GameState(None, beehive, ant_types(), layout, dimensions) 43 | """, 44 | 'teardown': '', 45 | 'type': 'doctest' 46 | }, 47 | { 48 | 'cases': [ 49 | { 50 | 'code': r""" 51 | >>> from ants import * 52 | >>> LaserAnt.implemented 53 | True 54 | """, 55 | 'hidden': False, 56 | 'locked': False 57 | } 58 | ], 59 | 'scored': True, 60 | 'setup': '', 61 | 'teardown': '', 62 | 'type': 'doctest' 63 | } 64 | ] 65 | } 66 | -------------------------------------------------------------------------------- /projects/ants/ucb.py: -------------------------------------------------------------------------------- 1 | """The UCB module contains functions specific to 61A projects at UC Berkeley.""" 2 | 3 | from __future__ import print_function 4 | 5 | import code 6 | import functools 7 | import inspect 8 | import re 9 | import signal 10 | import sys 11 | 12 | 13 | def main(fn): 14 | """Call fn with command line arguments. Used as a decorator. 15 | 16 | The main decorator marks the function that starts a program. For example, 17 | 18 | @main 19 | def my_run_function(): 20 | # function body 21 | 22 | Use this instead of the typical __name__ == "__main__" predicate. 23 | """ 24 | if inspect.stack()[1][0].f_locals['__name__'] == '__main__': 25 | args = sys.argv[1:] # Discard the script name from command line 26 | fn(*args) # Call the main function 27 | return fn 28 | 29 | _PREFIX = '' 30 | def trace(fn): 31 | """A decorator that prints a function's name, its arguments, and its return 32 | values each time the function is called. For example, 33 | 34 | @trace 35 | def compute_something(x, y): 36 | # function body 37 | """ 38 | @functools.wraps(fn) 39 | def wrapped(*args, **kwds): 40 | global _PREFIX 41 | reprs = [repr(e) for e in args] 42 | reprs += [repr(k) + '=' + repr(v) for k, v in kwds.items()] 43 | log('{0}({1})'.format(fn.__name__, ', '.join(reprs)) + ':') 44 | _PREFIX += ' ' 45 | try: 46 | result = fn(*args, **kwds) 47 | _PREFIX = _PREFIX[:-4] 48 | except Exception as e: 49 | log(fn.__name__ + ' exited via exception') 50 | _PREFIX = _PREFIX[:-4] 51 | raise 52 | # Here, print out the return value. 53 | log('{0}({1}) -> {2}'.format(fn.__name__, ', '.join(reprs), result)) 54 | return result 55 | return wrapped 56 | 57 | 58 | def log(message): 59 | """Print an indented message (used with trace).""" 60 | print(_PREFIX + re.sub('\n', '\n' + _PREFIX, str(message))) 61 | 62 | 63 | def log_current_line(): 64 | """Print information about the current line of code.""" 65 | frame = inspect.stack()[1] 66 | log('Current line: File "{f[1]}", line {f[2]}, in {f[3]}'.format(f=frame)) 67 | 68 | 69 | def interact(msg=None): 70 | """Start an interactive interpreter session in the current environment. 71 | 72 | On Unix: 73 | -D exits the interactive session and returns to normal execution. 74 | In Windows: 75 | -Z exits the interactive session and returns to normal 76 | execution. 77 | """ 78 | # evaluate commands in current namespace 79 | frame = inspect.currentframe().f_back 80 | namespace = frame.f_globals.copy() 81 | namespace.update(frame.f_locals) 82 | 83 | # exit on interrupt 84 | def handler(signum, frame): 85 | print() 86 | exit(0) 87 | signal.signal(signal.SIGINT, handler) 88 | 89 | if not msg: 90 | _, filename, line, _, _, _ = inspect.stack()[1] 91 | msg = 'Interacting at File "{0}", line {1} \n'.format(filename, line) 92 | msg += ' Unix: -D continues the program; \n' 93 | msg += ' Windows: -Z continues the program; \n' 94 | msg += ' exit() or -C exits the program' 95 | 96 | code.interact(msg, None, namespace) -------------------------------------------------------------------------------- /projects/ants/utils.py: -------------------------------------------------------------------------------- 1 | def class_method_wrapper(method, pre=None, post=None): 2 | """Given a class METHOD and two wrapper function, a PRE-function and 3 | POST-function, first calls the pre-wrapper, calls the wrapped class method, 4 | and then calls the post-wrapper. 5 | 6 | All wrappers should have the parameters (self, rv, *args). However, 7 | pre-wrappers will always have `None` passed in as `rv`, since a return 8 | value has not been evaluated yet. 9 | 10 | >>> def pre_wrapper(instance, rv, *args): 11 | ... print('Pre-wrapper called: {0}'.format(args)) 12 | >>> def post_wrapper(instance, rv, *args): 13 | ... print('Post-wrapper called: {0} -> {1}'.format(args, rv)) 14 | >>> class Foo(object): 15 | ... def __init__(self): 16 | ... self.bar = 20 17 | ... def method(self, var1, var2): 18 | ... print('Original method called') 19 | ... return var1 + var2 + self.bar 20 | >>> Foo.method = class_method_wrapper(Foo.method, pre_wrapper, post_wrapper) 21 | >>> f = Foo() 22 | >>> x = f.method(1, 2) 23 | Pre-wrapper called: (1, 2) 24 | Original method called 25 | Post-wrapper called: (1, 2) -> 23 26 | >>> x 27 | 23 28 | """ 29 | def wrapped_method(self, *args): 30 | pre(self, None, *args) if pre else None 31 | rv = method(self, *args) 32 | post(self, rv, *args) if post else None 33 | return rv 34 | return wrapped_method 35 | 36 | def print_expired_insects(self, rv, *args): 37 | """Post-wrapper for Insect.reduce_armor, and will print a message if the 38 | insect has expired (armor reduced to 0). 39 | 40 | >>> from ants import Insect, Bee, ThrowerAnt, Place 41 | >>> Insect.reduce_armor = class_method_wrapper(Insect.reduce_armor, 42 | ... pre=print_expired_insects) 43 | >>> place = Place('Test') 44 | >>> bee = Bee(3) 45 | >>> place.add_insect(bee) 46 | >>> bee.reduce_armor(2) 47 | >>> bee.reduce_armor(1) 48 | Bee(Test) ran out of armor and expired 49 | >>> thrower = ThrowerAnt() 50 | >>> place.add_insect(thrower) 51 | >>> thrower.reduce_armor(1) 52 | ThrowerAnt(Test) ran out of armor and expired 53 | """ 54 | if self.armor <= args[0]: 55 | print('{0}({1}) ran out of armor and expired'.format( 56 | type(self).__name__, self.place)) 57 | 58 | def print_thrower_target(self, rv, *args): 59 | """Prints the target of a ThrowerAnt, if the ThrowerAnt found a target. 60 | 61 | >>> from ants import * 62 | >>> beehive = Hive(AssaultPlan()) 63 | >>> dimensions = (1, 9) 64 | >>> gamestate = GameState(None, beehive, ant_types(), dry_layout, dimensions) 65 | >>> ThrowerAnt.nearest_bee = class_method_wrapper(ThrowerAnt.nearest_bee, 66 | ... post=print_thrower_target) 67 | >>> thrower = ThrowerAnt() 68 | >>> short = ShortThrower() 69 | >>> bee = Bee(5) 70 | >>> gamestate.places['tunnel_0_1'].add_insect(short) 71 | >>> gamestate.places['tunnel_0_0'].add_insect(thrower) 72 | >>> gamestate.places['tunnel_0_5'].add_insect(bee) 73 | >>> thrower.action(gamestate) 74 | ThrowerAnt(1, tunnel_0_0) targeted Bee(5, tunnel_0_5) 75 | >>> short.action(gamestate) # Bee not in range of ShortThrower 76 | >>> bee.action(gamestate) # Bee moves into range 77 | >>> short.action(gamestate) 78 | ShortThrower(1, tunnel_0_1) targeted Bee(4, tunnel_0_4) 79 | """ 80 | if rv is not None: 81 | print('{0} targeted {1}'.format(self, rv)) -------------------------------------------------------------------------------- /projects/cats/gui_files/FreeMono.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/FreeMono.ttf -------------------------------------------------------------------------------- /projects/cats/gui_files/__pycache__/common_server.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/__pycache__/common_server.cpython-39.pyc -------------------------------------------------------------------------------- /projects/cats/gui_files/__pycache__/db.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/__pycache__/db.cpython-39.pyc -------------------------------------------------------------------------------- /projects/cats/gui_files/__pycache__/leaderboard_integrity.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/__pycache__/leaderboard_integrity.cpython-39.pyc -------------------------------------------------------------------------------- /projects/cats/gui_files/__pycache__/multiplayer.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/__pycache__/multiplayer.cpython-39.pyc -------------------------------------------------------------------------------- /projects/cats/gui_files/db.py: -------------------------------------------------------------------------------- 1 | import os 2 | from contextlib import contextmanager 3 | 4 | from time import sleep 5 | 6 | # noinspection PyUnresolvedReferences 7 | import __main__ 8 | 9 | NUM_RETRIES = 5 10 | SLEEP_DELAY = 2 11 | 12 | 13 | def setup_db(service_name): 14 | from sqlalchemy import create_engine 15 | global engine 16 | engine = create_engine(os.getenv("DATABASE_URL", "mysql://localhost/{}".format(service_name))) 17 | 18 | 19 | @contextmanager 20 | def connect_db(): 21 | from sqlalchemy.exc import OperationalError 22 | 23 | def db(*args): 24 | for _ in range(NUM_RETRIES): 25 | with engine.connect() as conn: 26 | try: 27 | try: 28 | if isinstance(args[1][0], str): 29 | raise TypeError 30 | except (IndexError, TypeError): 31 | return conn.execute(*args) 32 | else: 33 | for data in args[1]: 34 | conn.execute(args[0], data, *args[2:]) 35 | except OperationalError as e: 36 | print("MySQL Failure, retrying in {} seconds...".format(SLEEP_DELAY), e) 37 | sleep(SLEEP_DELAY) 38 | continue 39 | else: 40 | break 41 | else: 42 | print("{} repeated failures, transaction failed".format(NUM_RETRIES)) 43 | 44 | yield db 45 | -------------------------------------------------------------------------------- /projects/cats/gui_files/favicons/crying.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/favicons/crying.ico -------------------------------------------------------------------------------- /projects/cats/gui_files/favicons/grinning.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/favicons/grinning.ico -------------------------------------------------------------------------------- /projects/cats/gui_files/favicons/heart-eyes.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/favicons/heart-eyes.ico -------------------------------------------------------------------------------- /projects/cats/gui_files/favicons/kissing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/favicons/kissing.png -------------------------------------------------------------------------------- /projects/cats/gui_files/favicons/pouting.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/favicons/pouting.ico -------------------------------------------------------------------------------- /projects/cats/gui_files/favicons/smiling.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/favicons/smiling.ico -------------------------------------------------------------------------------- /projects/cats/gui_files/favicons/tears-of-joy.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/favicons/tears-of-joy.ico -------------------------------------------------------------------------------- /projects/cats/gui_files/favicons/weary.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/favicons/weary.ico -------------------------------------------------------------------------------- /projects/cats/gui_files/favicons/wry.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/cats/gui_files/favicons/wry.ico -------------------------------------------------------------------------------- /projects/cats/gui_files/index.html: -------------------------------------------------------------------------------- 1 | Cats
-------------------------------------------------------------------------------- /projects/cats/gui_files/leaderboard_integrity.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | import os 4 | import random 5 | import time 6 | from functools import wraps 7 | from queue import Queue 8 | from threading import Thread 9 | 10 | import cats 11 | 12 | fernet = None 13 | 14 | COMMON_WORDS_SET = set(cats.lines_from_file('data/common_words.txt')) 15 | CAPTCHA_QUEUE_LEN = 200 16 | CAPTCHA_LENGTH = 10 17 | CAPTCHA_WORD_LEN = 6 18 | 19 | captcha_queue = Queue() 20 | 21 | 22 | def require_fernet(f): 23 | @wraps(f) 24 | def wrapped(*args, **kwargs): 25 | global fernet 26 | if not fernet: 27 | from cryptography.fernet import Fernet 28 | fernet = Fernet(os.environ.get("FERNET_KEY", Fernet.generate_key())) 29 | return f(*args, **kwargs) 30 | 31 | return wrapped 32 | 33 | 34 | def token_writer(f): 35 | @wraps(f) 36 | @require_fernet 37 | def wrapped(*args, **kwargs): 38 | data = f(*args, **kwargs) 39 | decoded = json.dumps(data).encode("utf-8") 40 | return fernet.encrypt(decoded).decode("utf-8") 41 | return wrapped 42 | 43 | 44 | def token_reader(fail): 45 | def decorator(f): 46 | @wraps(f) 47 | @require_fernet 48 | def wrapped(*, token, **kwargs): 49 | from cryptography.fernet import InvalidToken 50 | if not token: 51 | return fail 52 | try: 53 | return f(token=json.loads(fernet.decrypt(token.encode("utf-8"))), **kwargs) 54 | except (TypeError, InvalidToken): 55 | return fail 56 | return wrapped 57 | return decorator 58 | 59 | 60 | @token_writer 61 | def create_wpm_authorization(user, wpm): 62 | return { 63 | "user": user, 64 | "wpm": wpm, 65 | } 66 | 67 | 68 | @token_reader(fail=0) 69 | def get_authorized_limit(user, token): 70 | if token["user"] != user: 71 | return 0 72 | return token["wpm"] 73 | 74 | 75 | @token_writer 76 | def encode_challenge(user, words): 77 | return { 78 | "user": user, 79 | "words": words, 80 | "startTime": time.time(), 81 | } 82 | 83 | 84 | @token_reader(fail=(False, False)) 85 | def decode_challenge(token): 86 | return token["user"], token["words"], token["startTime"] 87 | 88 | 89 | def populate_captcha_queue(): 90 | while captcha_queue.qsize() < CAPTCHA_QUEUE_LEN: 91 | captcha_queue.put(generate_captcha()) 92 | 93 | 94 | def generate_captcha(): 95 | from claptcha import Claptcha 96 | word = random.choice([x for x in COMMON_WORDS_SET if len(x) < CAPTCHA_LENGTH]) 97 | c = Claptcha(word, "gui_files/FreeMono.ttf", margin=(20, 10)) 98 | image_b64 = base64.b64encode(c.bytes[1].getvalue()).decode("utf-8") 99 | return "data:image/png;base64," + image_b64, word 100 | 101 | 102 | def get_captcha_urls(num_words=CAPTCHA_LENGTH): 103 | Thread(target=populate_captcha_queue).start() 104 | 105 | images, words = [], [] 106 | for _ in range(num_words): 107 | image, word = captcha_queue.get() 108 | images.append(image) 109 | words.append(word) 110 | 111 | return images, words 112 | -------------------------------------------------------------------------------- /projects/cats/gui_files/precache-manifest.10080bcf5f16dc96f6d8a14870c1bcfe.js: -------------------------------------------------------------------------------- 1 | self.__precacheManifest = (self.__precacheManifest || []).concat([ 2 | { 3 | "revision": "67088ed990d52e547d6bb9fc92186c7e", 4 | "url": "/index.html" 5 | }, 6 | { 7 | "revision": "7590f4baa4041af48714", 8 | "url": "/static/css/2.df9ef6f4.chunk.css" 9 | }, 10 | { 11 | "revision": "16ad76164f3fdd58d685", 12 | "url": "/static/css/main.a9291ed5.chunk.css" 13 | }, 14 | { 15 | "revision": "7590f4baa4041af48714", 16 | "url": "/static/js/2.5cb2d1bf.chunk.js" 17 | }, 18 | { 19 | "revision": "16ad76164f3fdd58d685", 20 | "url": "/static/js/main.2b5aa836.chunk.js" 21 | }, 22 | { 23 | "revision": "42ac5946195a7306e2a5", 24 | "url": "/static/js/runtime~main.a8a9905a.js" 25 | } 26 | ]); -------------------------------------------------------------------------------- /projects/cats/gui_files/precache-manifest.544d7034191ecf52fa7c157490579669.js: -------------------------------------------------------------------------------- 1 | self.__precacheManifest = (self.__precacheManifest || []).concat([ 2 | { 3 | "revision": "991091c13af4d8fb33ce7527ed37dd8a", 4 | "url": "/index.html" 5 | }, 6 | { 7 | "revision": "7590f4baa4041af48714", 8 | "url": "/static/css/2.df9ef6f4.chunk.css" 9 | }, 10 | { 11 | "revision": "610c8a555b71b8b2229b", 12 | "url": "/static/css/main.a9291ed5.chunk.css" 13 | }, 14 | { 15 | "revision": "7590f4baa4041af48714", 16 | "url": "/static/js/2.5cb2d1bf.chunk.js" 17 | }, 18 | { 19 | "revision": "610c8a555b71b8b2229b", 20 | "url": "/static/js/main.c5c6e95b.chunk.js" 21 | }, 22 | { 23 | "revision": "42ac5946195a7306e2a5", 24 | "url": "/static/js/runtime~main.a8a9905a.js" 25 | } 26 | ]); -------------------------------------------------------------------------------- /projects/cats/gui_files/static/css/main.a9291ed5.chunk.css: -------------------------------------------------------------------------------- 1 | body{margin:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}code{font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}.App{text-align:center}.App-logo{-webkit-animation:App-logo-spin 20s linear infinite;animation:App-logo-spin 20s linear infinite;height:40vmin;pointer-events:none}.App-header{background-color:#282c34;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:calc(10px + 2vmin);color:#fff}.App-link{color:#61dafb}.LeaderboardButton{float:right;display:flex;flex-direction:column}.LeaderboardButton button+button{margin-top:5px}@-webkit-keyframes App-logo-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes App-logo-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.Input{width:100%;text-align:left}.InputBox{border:2px solid green;padding:10px;cursor:text}.InputField{display:inline-block;height:24px;border:none;outline:none;min-width:5px}.TypedWord{white-space:pre-wrap}.updated{color:green;font-weight:700}.incorrect{color:red;font-weight:700}.both{color:orange;font-weight:700}.Indicator{display:inline-block;border:2px solid #000;padding:10px;margin-left:20px;margin-right:20px;width:160px}.Indicators{width:100%}.Entries{align-items:left}.Entries,.Footer{display:flex;flex-direction:column;font-size:14px;width:-webkit-fill-available}.Footer{align-items:center}.Header{display:flex;font-size:20px;width:-webkit-fill-available}#Title,.Header{color:#000;font-weight:700}#Title{font-size:16px}.Entry{text-align:left}.Rank{font-weight:700}.Rank:after{content:". "}.Name{font-style:italic}.Score:after{content:" wpm - "}.Spinner{width:-webkit-fill-available;display:flex;align-items:center;flex-direction:column}.Button,.Options{text-align:left}.Prompt,.PromptBox{text-align:left}.Prompt{border:2px solid purple;padding:10px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.Character{white-space:pre-wrap}.correct{background-color:#90ee90}.wrong{background-color:pink}.ProgressBar{margin:4px}.progress{display:inline-block;width:calc(100% - 140px);height:40px;vertical-align:bottom}.progress-bar{height:100%}.ProgressBars{align-items:space-around;display:flex;flex-direction:column;margin:16px}.ProgressBars .barData{display:inline-block;width:140px;text-align:left;padding-left:5px;line-height:40px;vertical-align:bottom}.CaptchaChallenge .images img{height:2rem;border-bottom:5px solid transparent;box-sizing:content-box}.CaptchaChallenge .images{border:2px solid purple;padding:10px;text-align:center;cursor:text;line-height:2.5rem}.CaptchaChallenge .activeImage.activeImage{border-bottom:5px solid green}.TopicPicker{text-align:left} 2 | /*# sourceMappingURL=main.a9291ed5.chunk.css.map */ -------------------------------------------------------------------------------- /projects/cats/gui_files/static/js/runtime~main.a8a9905a.js: -------------------------------------------------------------------------------- 1 | !function(e){function r(r){for(var n,f,i=r[0],l=r[1],a=r[2],c=0,s=[];c'.format(self.a, self.b) 59 | 60 | game = Game 61 | word_at = lambda u, v: u.a[v] 62 | all_words = lambda u: u.a 63 | all_times = lambda u: u.b 64 | time = lambda u, v, w: u.b[v][w] 65 | 66 | old = {} 67 | 68 | def swap_implementations(impl): 69 | # save other implementations 70 | old['game'] = impl.game, impl.word_at, impl.all_words, impl.all_times, impl.time 71 | 72 | # save our implementations 73 | new_game = game, word_at, all_words, all_times, time 74 | 75 | # replace impl's implementations with ours 76 | impl.game, impl.word_at, impl.all_words, impl.all_times, impl.time = game, word_at, all_words, all_times, time 77 | 78 | def restore_implementations(impl): 79 | impl.game, impl.word_at, impl.all_words, impl.all_times, impl.time = old['game'] 80 | -------------------------------------------------------------------------------- /projects/hog/dice.py: -------------------------------------------------------------------------------- 1 | """Functions that simulate dice rolls. 2 | 3 | A dice function takes no arguments and returns a number from 1 to n 4 | (inclusive), where n is the number of sides on the dice. 5 | 6 | Types of dice: 7 | 8 | - Dice can be fair, meaning that they produce each possible outcome with equal 9 | probability. Examples: four_sided, six_sided 10 | 11 | - For testing functions that use dice, deterministic test dice always cycle 12 | through a fixed sequence of values that are passed as arguments to the 13 | make_test_dice function. 14 | """ 15 | 16 | from random import randint 17 | 18 | def make_fair_dice(sides): 19 | """Return a die that returns 1 to SIDES with equal chance.""" 20 | assert type(sides) == int and sides >= 1, 'Illegal value for sides' 21 | def dice(): 22 | return randint(1,sides) 23 | return dice 24 | 25 | four_sided = make_fair_dice(4) 26 | six_sided = make_fair_dice(6) 27 | 28 | def make_test_dice(*outcomes): 29 | """Return a die that cycles deterministically through OUTCOMES. 30 | 31 | >>> dice = make_test_dice(1, 2, 3) 32 | >>> dice() 33 | 1 34 | >>> dice() 35 | 2 36 | >>> dice() 37 | 3 38 | >>> dice() 39 | 1 40 | >>> dice() 41 | 2 42 | 43 | This function uses Python syntax/techniques not yet covered in this course. 44 | The best way to understand it is by reading the documentation and examples. 45 | """ 46 | assert len(outcomes) > 0, 'You must supply outcomes to make_test_dice' 47 | for o in outcomes: 48 | assert type(o) == int and o >= 1, 'Outcome is not a positive integer' 49 | index = len(outcomes) - 1 50 | def dice(): 51 | nonlocal index 52 | index = (index + 1) % len(outcomes) 53 | return outcomes[index] 54 | return dice -------------------------------------------------------------------------------- /projects/hog/gui_files/__pycache__/common_server.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/hog/gui_files/__pycache__/common_server.cpython-39.pyc -------------------------------------------------------------------------------- /projects/hog/gui_files/favicon.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/hog/gui_files/favicon.gif -------------------------------------------------------------------------------- /projects/hog/gui_files/index.html: -------------------------------------------------------------------------------- 1 | The Game of Hog
-------------------------------------------------------------------------------- /projects/hog/gui_files/static/css/main.dfa42325.chunk.css: -------------------------------------------------------------------------------- 1 | body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Roboto","Oxygen","Ubuntu","Cantarell","Fira Sans","Droid Sans","Helvetica Neue",sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}code{font-family:source-code-pro,Menlo,Monaco,Consolas,"Courier New",monospace}*{box-sizing:border-box} 2 | /*# sourceMappingURL=main.dfa42325.chunk.css.map */ -------------------------------------------------------------------------------- /projects/hog/gui_files/static/js/2.14215b64.chunk.js.LICENSE: -------------------------------------------------------------------------------- 1 | /*! 2 | Copyright (c) 2017 Jed Watson. 3 | Licensed under the MIT License (MIT), see 4 | http://jedwatson.github.io/classnames 5 | */ 6 | 7 | /* 8 | object-assign 9 | (c) Sindre Sorhus 10 | @license MIT 11 | */ 12 | 13 | /** @license React v16.12.0 14 | * react.production.min.js 15 | * 16 | * Copyright (c) Facebook, Inc. and its affiliates. 17 | * 18 | * This source code is licensed under the MIT license found in the 19 | * LICENSE file in the root directory of this source tree. 20 | */ 21 | 22 | /** @license React v16.12.0 23 | * react-dom.production.min.js 24 | * 25 | * Copyright (c) Facebook, Inc. and its affiliates. 26 | * 27 | * This source code is licensed under the MIT license found in the 28 | * LICENSE file in the root directory of this source tree. 29 | */ 30 | 31 | /** @license React v0.18.0 32 | * scheduler.production.min.js 33 | * 34 | * Copyright (c) Facebook, Inc. and its affiliates. 35 | * 36 | * This source code is licensed under the MIT license found in the 37 | * LICENSE file in the root directory of this source tree. 38 | */ 39 | 40 | /** @license React v16.12.0 41 | * react-is.production.min.js 42 | * 43 | * Copyright (c) Facebook, Inc. and its affiliates. 44 | * 45 | * This source code is licensed under the MIT license found in the 46 | * LICENSE file in the root directory of this source tree. 47 | */ 48 | -------------------------------------------------------------------------------- /projects/hog/gui_files/static/js/2.36722391.chunk.js.LICENSE: -------------------------------------------------------------------------------- 1 | /*! 2 | Copyright (c) 2017 Jed Watson. 3 | Licensed under the MIT License (MIT), see 4 | http://jedwatson.github.io/classnames 5 | */ 6 | 7 | /* 8 | object-assign 9 | (c) Sindre Sorhus 10 | @license MIT 11 | */ 12 | 13 | /** @license React v16.12.0 14 | * react.production.min.js 15 | * 16 | * Copyright (c) Facebook, Inc. and its affiliates. 17 | * 18 | * This source code is licensed under the MIT license found in the 19 | * LICENSE file in the root directory of this source tree. 20 | */ 21 | 22 | /** @license React v16.12.0 23 | * react-dom.production.min.js 24 | * 25 | * Copyright (c) Facebook, Inc. and its affiliates. 26 | * 27 | * This source code is licensed under the MIT license found in the 28 | * LICENSE file in the root directory of this source tree. 29 | */ 30 | 31 | /** @license React v0.18.0 32 | * scheduler.production.min.js 33 | * 34 | * Copyright (c) Facebook, Inc. and its affiliates. 35 | * 36 | * This source code is licensed under the MIT license found in the 37 | * LICENSE file in the root directory of this source tree. 38 | */ 39 | 40 | /** @license React v16.12.0 41 | * react-is.production.min.js 42 | * 43 | * Copyright (c) Facebook, Inc. and its affiliates. 44 | * 45 | * This source code is licensed under the MIT license found in the 46 | * LICENSE file in the root directory of this source tree. 47 | */ 48 | -------------------------------------------------------------------------------- /projects/hog/gui_files/static/js/2.50b6458a.chunk.js.LICENSE.txt: -------------------------------------------------------------------------------- 1 | /* 2 | object-assign 3 | (c) Sindre Sorhus 4 | @license MIT 5 | */ 6 | 7 | /*! 8 | Copyright (c) 2017 Jed Watson. 9 | Licensed under the MIT License (MIT), see 10 | http://jedwatson.github.io/classnames 11 | */ 12 | 13 | /** @license React v0.19.1 14 | * scheduler.production.min.js 15 | * 16 | * Copyright (c) Facebook, Inc. and its affiliates. 17 | * 18 | * This source code is licensed under the MIT license found in the 19 | * LICENSE file in the root directory of this source tree. 20 | */ 21 | 22 | /** @license React v16.13.1 23 | * react-dom.production.min.js 24 | * 25 | * Copyright (c) Facebook, Inc. and its affiliates. 26 | * 27 | * This source code is licensed under the MIT license found in the 28 | * LICENSE file in the root directory of this source tree. 29 | */ 30 | 31 | /** @license React v16.13.1 32 | * react-is.production.min.js 33 | * 34 | * Copyright (c) Facebook, Inc. and its affiliates. 35 | * 36 | * This source code is licensed under the MIT license found in the 37 | * LICENSE file in the root directory of this source tree. 38 | */ 39 | 40 | /** @license React v16.13.1 41 | * react.production.min.js 42 | * 43 | * Copyright (c) Facebook, Inc. and its affiliates. 44 | * 45 | * This source code is licensed under the MIT license found in the 46 | * LICENSE file in the root directory of this source tree. 47 | */ 48 | -------------------------------------------------------------------------------- /projects/hog/gui_files/static/js/2.cbd40270.chunk.js.LICENSE: -------------------------------------------------------------------------------- 1 | /* 2 | object-assign 3 | (c) Sindre Sorhus 4 | @license MIT 5 | */ 6 | 7 | /*! 8 | Copyright (c) 2017 Jed Watson. 9 | Licensed under the MIT License (MIT), see 10 | http://jedwatson.github.io/classnames 11 | */ 12 | 13 | /** @license React v0.18.0 14 | * scheduler.production.min.js 15 | * 16 | * Copyright (c) Facebook, Inc. and its affiliates. 17 | * 18 | * This source code is licensed under the MIT license found in the 19 | * LICENSE file in the root directory of this source tree. 20 | */ 21 | 22 | /** @license React v16.12.0 23 | * react-dom.production.min.js 24 | * 25 | * Copyright (c) Facebook, Inc. and its affiliates. 26 | * 27 | * This source code is licensed under the MIT license found in the 28 | * LICENSE file in the root directory of this source tree. 29 | */ 30 | 31 | /** @license React v16.12.0 32 | * react-is.production.min.js 33 | * 34 | * Copyright (c) Facebook, Inc. and its affiliates. 35 | * 36 | * This source code is licensed under the MIT license found in the 37 | * LICENSE file in the root directory of this source tree. 38 | */ 39 | 40 | /** @license React v16.13.1 41 | * react.production.min.js 42 | * 43 | * Copyright (c) Facebook, Inc. and its affiliates. 44 | * 45 | * This source code is licensed under the MIT license found in the 46 | * LICENSE file in the root directory of this source tree. 47 | */ 48 | -------------------------------------------------------------------------------- /projects/hog/gui_files/static/js/runtime-main.53f79363.js: -------------------------------------------------------------------------------- 1 | !function(e){function r(r){for(var n,i,l=r[0],f=r[1],a=r[2],c=0,s=[];c>> test_dice = make_test_dice(4, 1, 2) 10 | >>> test_dice() 11 | 4 12 | >>> test_dice() # Second call 13 | 1 14 | >>> test_dice() # Third call 15 | 2 16 | >>> test_dice() # Fourth call 17 | 4 18 | """, 19 | 'hidden': False, 20 | 'locked': False 21 | } 22 | ], 23 | 'scored': True, 24 | 'setup': r""" 25 | >>> from hog import * 26 | """, 27 | 'teardown': '', 28 | 'type': 'doctest' 29 | }, 30 | { 31 | 'cases': [ 32 | { 33 | 'answer': 'six_sided()', 34 | 'choices': [ 35 | 'make_test_dice(6)', 36 | 'make_fair_dice(6)', 37 | 'six_sided', 38 | 'six_sided()' 39 | ], 40 | 'hidden': False, 41 | 'locked': False, 42 | 'question': 'Which of the following is the correct way to "roll" a fair, six-sided die?' 43 | } 44 | ], 45 | 'scored': False, 46 | 'type': 'concept' 47 | } 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /projects/hog/tests/03.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Question 3', 3 | 'points': 2, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> take_turn(2, 0, make_test_dice(4, 5, 1)) 10 | 9 11 | """, 12 | 'hidden': False, 13 | 'locked': False 14 | }, 15 | { 16 | 'code': r""" 17 | >>> take_turn(3, 0, make_test_dice(4, 6, 1)) 18 | 1 19 | """, 20 | 'hidden': False, 21 | 'locked': False 22 | }, 23 | { 24 | 'code': r""" 25 | >>> take_turn(0, 2) 26 | 7 27 | """, 28 | 'hidden': False, 29 | 'locked': False 30 | }, 31 | { 32 | 'code': r""" 33 | >>> take_turn(0, 0) 34 | 6 35 | """, 36 | 'hidden': False, 37 | 'locked': False 38 | }, 39 | { 40 | 'code': r""" 41 | >>> take_turn(0, 1) 42 | 4 43 | """, 44 | 'hidden': False, 45 | 'locked': False 46 | }, 47 | { 48 | 'code': r""" 49 | >>> take_turn(2, 0, make_test_dice(6)) 50 | 12 51 | """, 52 | 'hidden': False, 53 | 'locked': False 54 | }, 55 | { 56 | 'code': r""" 57 | >>> take_turn(9, 0, make_test_dice(4)) 58 | 36 59 | """, 60 | 'hidden': False, 61 | 'locked': False 62 | }, 63 | { 64 | 'code': r""" 65 | >>> take_turn(7, 0, make_test_dice(4)) 66 | 28 67 | """, 68 | 'hidden': False, 69 | 'locked': False 70 | }, 71 | { 72 | 'code': r""" 73 | >>> take_turn(8, 0, make_test_dice(5)) 74 | 40 75 | """, 76 | 'hidden': False, 77 | 'locked': False 78 | } 79 | ], 80 | 'scored': True, 81 | 'setup': r""" 82 | >>> from hog import * 83 | """, 84 | 'teardown': '', 85 | 'type': 'doctest' 86 | }, 87 | { 88 | 'cases': [ 89 | { 90 | 'code': r""" 91 | >>> hog.take_turn(5, 0) # Make sure you call roll_dice! 92 | Called roll dice! 93 | 9002 94 | """, 95 | 'hidden': False, 96 | 'locked': False 97 | } 98 | ], 99 | 'scored': True, 100 | 'setup': r""" 101 | >>> import hog 102 | >>> def roll_dice(num_rolls, dice): 103 | ... print("Called roll dice!") 104 | ... return 9002 105 | ... 106 | >>> hog.roll_dice, old_roll_dice = roll_dice, hog.roll_dice 107 | """, 108 | 'teardown': r""" 109 | >>> hog.roll_dice = old_roll_dice 110 | """, 111 | 'type': 'doctest' 112 | } 113 | ] 114 | } 115 | -------------------------------------------------------------------------------- /projects/hog/tests/07.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Question 7', 3 | 'points': 3, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'answer': 'A commentary function that prints information about the biggest point increase for the current player.', 9 | 'choices': [ 10 | r""" 11 | A commentary function that prints information about the 12 | biggest point increase for the current player. 13 | """, 14 | r""" 15 | A string containing the largest point increase for the 16 | current player. 17 | """, 18 | r""" 19 | The current largest point increase between both 20 | players. 21 | """ 22 | ], 23 | 'hidden': False, 24 | 'locked': False, 25 | 'question': 'What does announce_highest return?' 26 | }, 27 | { 28 | 'answer': 'When the current player, given by the parameter `who`, earns their biggest point increase yet in the game.', 29 | 'choices': [ 30 | r""" 31 | When the current player, given by the parameter `who`, 32 | earns their biggest point increase yet in the game. 33 | """, 34 | 'After each turn.', 35 | r""" 36 | When the current player, given by the parameter `who`, 37 | earns the biggest point increase yet between both 38 | players in the game. 39 | """ 40 | ], 41 | 'hidden': False, 42 | 'locked': False, 43 | 'question': r""" 44 | When does the commentary function returned by announce_highest 45 | print something out? 46 | """ 47 | }, 48 | { 49 | 'answer': "The current player's score before this turn.", 50 | 'choices': [ 51 | 'The last highest gain for the current player.', 52 | "The current player's score before this turn.", 53 | "The opponent's score before this turn." 54 | ], 55 | 'hidden': False, 56 | 'locked': False, 57 | 'question': 'What does the parameter last_score represent?' 58 | } 59 | ], 60 | 'scored': False, 61 | 'type': 'concept' 62 | }, 63 | { 64 | 'cases': [ 65 | { 66 | 'code': r""" 67 | >>> # this might not technically be a possible game for the current rules, this shouldn't be relevant 68 | >>> f0 = announce_highest(1) # Only announce Player 1 score gains 69 | >>> f1 = f0(12, 0) 70 | >>> f2 = f1(12, 10) 71 | 10 point(s)! The most yet for Player 1 72 | >>> f3 = f2(20, 10) 73 | >>> f4 = f3(22, 20) 74 | >>> f5 = f4(22, 35) 75 | 15 point(s)! The most yet for Player 1 76 | >>> f6 = f5(30, 47) # Player 1 gets 12 points; not enough for a new high 77 | >>> f7 = f6(31, 47) 78 | >>> f8 = f7(32, 77) 79 | 30 point(s)! The most yet for Player 1 80 | >>> f9 = f8(83, 32) 81 | >>> f10 = f9(38, 83) 82 | 51 point(s)! The most yet for Player 1 83 | >>> # The following function call checks if the behavior of f1 changes, 84 | >>> # perhaps due to a side effect other than printing. The only side 85 | >>> # effect of a commentary function should be to print. 86 | >>> f2_again = f1(11, 9) 87 | 9 point(s)! The most yet for Player 1 88 | """, 89 | 'hidden': False, 90 | 'locked': False 91 | }, 92 | { 93 | 'code': r""" 94 | >>> # 95 | >>> announce_both = both(announce_highest(0), announce_highest(1)) 96 | >>> s0, s1 = play(always_roll(1), always_roll(1), dice=make_test_dice(5, 3, 5), goal=10, say=announce_both) 97 | 5 point(s)! The most yet for Player 0 98 | 3 point(s)! The most yet for Player 1 99 | 5 point(s)! The most yet for Player 1 100 | """, 101 | 'hidden': False, 102 | 'locked': False 103 | } 104 | ], 105 | 'scored': True, 106 | 'setup': r""" 107 | >>> from hog import play, always_roll, announce_highest, both 108 | >>> from dice import make_test_dice 109 | """, 110 | 'teardown': '', 111 | 'type': 'doctest' 112 | } 113 | ] 114 | } 115 | -------------------------------------------------------------------------------- /projects/hog/tests/08.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Question 8', 3 | 'points': 2, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'answer': 'It both takes in a function as an argument and returns a function', 9 | 'choices': [ 10 | 'It takes in a function as an argument', 11 | 'It returns a function', 12 | 'It both takes in a function as an argument and returns a function', 13 | 'It uses the *args keyword' 14 | ], 15 | 'hidden': False, 16 | 'locked': False, 17 | 'question': 'What makes make_averaged a higher order function?' 18 | }, 19 | { 20 | 'answer': 'An arbitrary amount, which is why we need to use *args to call it', 21 | 'choices': [ 22 | 'None', 23 | 'Two', 24 | 'An arbitrary amount, which is why we need to use *args to call it' 25 | ], 26 | 'hidden': False, 27 | 'locked': False, 28 | 'question': 'How many arguments does the function passed into make_averaged take?' 29 | } 30 | ], 31 | 'scored': False, 32 | 'type': 'concept' 33 | }, 34 | { 35 | 'cases': [ 36 | { 37 | 'code': r""" 38 | >>> dice = make_test_dice(3, 1, 5, 6) 39 | >>> averaged_dice = make_averaged(dice, 1000) 40 | >>> # Average of calling dice 1000 times 41 | >>> averaged_dice() 42 | 3.75 43 | """, 44 | 'hidden': False, 45 | 'locked': False 46 | }, 47 | { 48 | 'code': r""" 49 | >>> dice = make_test_dice(3, 1, 5, 6) 50 | >>> averaged_roll_dice = make_averaged(roll_dice, 1000) 51 | >>> # Average of calling roll_dice 1000 times 52 | >>> # Enter a float (e.g. 1.0) instead of an integer 53 | >>> averaged_roll_dice(2, dice) 54 | 6.0 55 | """, 56 | 'hidden': False, 57 | 'locked': False 58 | } 59 | ], 60 | 'scored': True, 61 | 'setup': r""" 62 | >>> from hog import * 63 | """, 64 | 'teardown': '', 65 | 'type': 'doctest' 66 | }, 67 | { 68 | 'cases': [ 69 | { 70 | 'code': r""" 71 | >>> hundred_range = range(1, 100) 72 | >>> hundred_dice = make_test_dice(*hundred_range) 73 | >>> averaged_hundred_dice = make_averaged(hundred_dice, 5*len(hundred_range)) 74 | >>> correct_average = sum(range(1, 100)) / len(hundred_range) 75 | >>> averaged_hundred_dice() 76 | 50.0 77 | >>> averaged_hundred_dice() 78 | 50.0 79 | """, 80 | 'hidden': False, 81 | 'locked': False 82 | }, 83 | { 84 | 'code': r""" 85 | >>> dice = make_test_dice(3, 1, 5, 6) 86 | >>> averaged_roll_dice = make_averaged(roll_dice, 1) 87 | >>> averaged_roll_dice(2, dice) 88 | 1.0 89 | """, 90 | 'hidden': False, 91 | 'locked': False 92 | }, 93 | { 94 | 'code': r""" 95 | >>> dice = make_test_dice(3, 1, 5, 6) 96 | >>> averaged_roll_dice = make_averaged(roll_dice, 5) 97 | >>> averaged_roll_dice(2, dice) 98 | 5.0 99 | """, 100 | 'hidden': False, 101 | 'locked': False 102 | } 103 | ], 104 | 'scored': True, 105 | 'setup': r""" 106 | >>> from hog import * 107 | """, 108 | 'teardown': '', 109 | 'type': 'doctest' 110 | } 111 | ] 112 | } 113 | -------------------------------------------------------------------------------- /projects/hog/tests/09.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Question 9', 3 | 'points': 2, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'answer': 'The lowest num_rolls', 9 | 'choices': [ 10 | 'The lowest num_rolls', 11 | 'The highest num_rolls', 12 | 'A random num_rolls' 13 | ], 14 | 'hidden': False, 15 | 'locked': False, 16 | 'question': r""" 17 | If multiple num_rolls are tied for the highest scoring 18 | average, which should you return? 19 | """ 20 | } 21 | ], 22 | 'scored': False, 23 | 'type': 'concept' 24 | }, 25 | { 26 | 'cases': [ 27 | { 28 | 'code': r""" 29 | >>> dice = make_test_dice(3) # dice always returns 3 30 | >>> max_scoring_num_rolls(dice, trials_count=1000) 31 | 10 32 | """, 33 | 'hidden': False, 34 | 'locked': False 35 | }, 36 | { 37 | 'code': r""" 38 | >>> dice = make_test_dice(1, 2, 2, 2, 2, 2, 2, 2) 39 | >>> max_scoring_num_rolls(dice, trials_count=1000) 40 | 4 41 | """, 42 | 'hidden': False, 43 | 'locked': False 44 | }, 45 | { 46 | 'code': r""" 47 | >>> dice = make_test_dice(*([2] * 55 + [1, 2] * 500)) # test that you are actually using trials_count 48 | >>> max_scoring_num_rolls(dice, trials_count=1) # dice is 2 for the first 55 rolls, then is 1 followed by 2 for 1000 rolls 49 | 10 50 | """, 51 | 'hidden': False, 52 | 'locked': False 53 | } 54 | ], 55 | 'scored': True, 56 | 'setup': r""" 57 | >>> from hog import * 58 | """, 59 | 'teardown': '', 60 | 'type': 'doctest' 61 | }, 62 | { 63 | 'cases': [ 64 | { 65 | 'code': r""" 66 | >>> dice = make_test_dice(2) # dice always rolls 2 67 | >>> max_scoring_num_rolls(dice, trials_count=1000) 68 | 10 69 | """, 70 | 'hidden': False, 71 | 'locked': False 72 | }, 73 | { 74 | 'code': r""" 75 | >>> dice = make_test_dice(1, 2) # dice alternates 1 and 2 76 | >>> max_scoring_num_rolls(dice, trials_count=1000) 77 | 1 78 | """, 79 | 'hidden': False, 80 | 'locked': False 81 | }, 82 | { 83 | 'code': r""" 84 | >>> # 100 2s and then 100 1s (don't worry about how this works) 85 | >>> dice = make_test_dice(*([2] * 100 + [1] * 100)) 86 | >>> max_scoring_num_rolls(dice, trials_count=1) 87 | 10 88 | """, 89 | 'hidden': False, 90 | 'locked': False 91 | }, 92 | { 93 | 'code': r""" 94 | >>> dice = make_test_dice(1, 2, 3, 4, 5) # dice sweeps from 1 through 5 95 | >>> max_scoring_num_rolls(dice, trials_count=1000) 96 | 3 97 | """, 98 | 'hidden': False, 99 | 'locked': False 100 | } 101 | ], 102 | 'scored': True, 103 | 'setup': r""" 104 | >>> from hog import * 105 | """, 106 | 'teardown': '', 107 | 'type': 'doctest' 108 | } 109 | ] 110 | } 111 | -------------------------------------------------------------------------------- /projects/hog/tests/12.py: -------------------------------------------------------------------------------- 1 | test = { 2 | 'name': 'Question 12', 3 | 'points': 0, 4 | 'suites': [ 5 | { 6 | 'cases': [ 7 | { 8 | 'code': r""" 9 | >>> check_strategy(hog.final_strategy) 10 | """, 11 | 'hidden': False, 12 | 'locked': False 13 | } 14 | ], 15 | 'scored': False, 16 | 'setup': r""" 17 | >>> import hog 18 | >>> def check_strategy(strat): 19 | ... for score in range(100): 20 | ... for opp in range(100): 21 | ... num_rolls = strat(score, opp) 22 | ... if not isinstance(num_rolls, int): 23 | ... raise ValueError("final_strategy({0}, {1}) returned {2}, not an int.".format(score, opp, num_rolls)) 24 | >>> def max_scoring_num_rolls(dice=lambda: 1): 25 | ... raise RuntimeError("Your final strategy should not call max_scoring_num_rolls.") 26 | >>> old_max_scoring_num_rolls = hog.max_scoring_num_rolls 27 | >>> hog.max_scoring_num_rolls = max_scoring_num_rolls 28 | """, 29 | 'teardown': r""" 30 | >>> hog.max_scoring_num_rolls = old_max_scoring_num_rolls 31 | """, 32 | 'type': 'doctest' 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /projects/hog/tests/check_strategy.py: -------------------------------------------------------------------------------- 1 | from hog import GOAL_SCORE 2 | 3 | def check_strategy_roll(score, opponent_score, num_rolls): 4 | """Raises an error with a helpful message if NUM_ROLLS is an invalid 5 | strategy output. All strategy outputs must be integers from 0 to 10. 6 | 7 | >>> check_strategy_roll(10, 20, num_rolls=100) 8 | Traceback (most recent call last): 9 | ... 10 | AssertionError: strategy(10, 20) returned 100 (invalid number of rolls) 11 | 12 | >>> check_strategy_roll(20, 10, num_rolls=0.1) 13 | Traceback (most recent call last): 14 | ... 15 | AssertionError: strategy(20, 10) returned 0.1 (not an integer) 16 | 17 | >>> check_strategy_roll(0, 0, num_rolls=None) 18 | Traceback (most recent call last): 19 | ... 20 | AssertionError: strategy(0, 0) returned None (not an integer) 21 | """ 22 | msg = 'strategy({}, {}) returned {}'.format( 23 | score, opponent_score, num_rolls) 24 | assert type(num_rolls) == int, msg + ' (not an integer)' 25 | assert 0 <= num_rolls <= 10, msg + ' (invalid number of rolls)' 26 | 27 | 28 | def check_strategy(strategy, goal=GOAL_SCORE): 29 | """Checks the strategy with all valid inputs and verifies that the strategy 30 | returns a valid output. Use `check_strategy_roll` to raise an error with a 31 | helpful message if the strategy returns an invalid output. 32 | 33 | >>> def fail_15_20(score, opponent_score): 34 | ... if score != 15 or opponent_score != 20: 35 | ... return 5 36 | ... 37 | >>> check_strategy(fail_15_20) 38 | Traceback (most recent call last): 39 | ... 40 | AssertionError: strategy(15, 20) returned None (not an integer) 41 | >>> def fail_102_115(score, opponent_score): 42 | ... if score == 102 and opponent_score == 115: 43 | ... return 100 44 | ... return 5 45 | ... 46 | >>> check_strategy(fail_102_115) 47 | >>> fail_102_115 == check_strategy(fail_102_115, 120) 48 | Traceback (most recent call last): 49 | ... 50 | AssertionError: strategy(102, 115) returned 100 (invalid number of rolls) 51 | """ 52 | for score in range(goal): 53 | for opponent_score in range(goal): 54 | num_rolls = strategy(score, opponent_score) 55 | check_strategy_roll(score, opponent_score, num_rolls) 56 | -------------------------------------------------------------------------------- /projects/hog/tests/play_utils.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | SUMMARY = "Start scores = ({s0}, {s1}).\nPlayer {w} rolls {nr} dice and gets outcomes {rv}.\nEnd scores = ({e0}, {e1})" 4 | 5 | def describe_game(hog, hog_gui, test_number, score0, score1, goal): 6 | strat_seed0, strat_seed1, dice_seed = run_with_seed(test_number, lambda: [random.randrange(2**32) for _ in range(3)]) 7 | strategy0 = random_strat(strat_seed0) 8 | strategy1 = random_strat(strat_seed1) 9 | dice = get_dice(dice_seed) 10 | s0last, s1last, game_trace = hog_gui.trace_play( 11 | hog.play, 12 | strategy0, 13 | strategy1, 14 | score0=score0, 15 | score1=score1, 16 | dice=dice, 17 | goal=goal, 18 | say=hog.silence) 19 | 20 | end_of_turn = [(turn["s0_start"], turn["s1_start"]) for turn in game_trace[1:]] 21 | end_of_turn.append((s0last, s1last)) 22 | summary = [] 23 | for turn, end in zip(game_trace, end_of_turn): 24 | summary.append(SUMMARY.format( 25 | s0=turn["s0_start"], 26 | s1=turn["s1_start"], 27 | w=turn["who"], 28 | nr=turn["num_dice"], 29 | rv=turn["dice_values"], 30 | e0=end[0], 31 | e1=end[1] 32 | )) 33 | summary.append("Game Over") 34 | return summary 35 | 36 | def random_strat(seed): 37 | """ 38 | Makes a random strategy from based on the given seed 39 | """ 40 | def random_strat(score, opponent_score): 41 | # Save the state of the random generator, so strategy calls don't 42 | # impact dice rolls. 43 | # using this because python's hash function is NOT CONSISTENT ACROSS OSs!!!!!!!!!!!!11!!22!!2! 44 | conditional_seed = score * 314159265358979 + opponent_score * 27182818284590452353602874713527 + seed * 161803398874989484820 45 | return run_with_seed(conditional_seed % (2 ** 32), lambda: random.randrange(0, 11)) 46 | return random_strat 47 | 48 | def run_with_seed(seed, fn): 49 | state = random.getstate() 50 | random.seed(seed) 51 | result = fn() 52 | random.setstate(state) 53 | return result 54 | 55 | def get_dice(seed): 56 | def dice(): 57 | nonlocal seed 58 | seed, value = run_with_seed(seed, lambda: (random.randrange(0, 2**32), random.randrange(1, 7))) 59 | return value 60 | return dice 61 | -------------------------------------------------------------------------------- /projects/scheme/__pycache__/scheme.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/scheme/__pycache__/scheme.cpython-39.pyc -------------------------------------------------------------------------------- /projects/scheme/__pycache__/scheme_reader.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/projects/scheme/__pycache__/scheme_reader.cpython-39.pyc -------------------------------------------------------------------------------- /projects/scheme/questions.scm: -------------------------------------------------------------------------------- 1 | (define (caar x) (car (car x))) 2 | (define (cadr x) (car (cdr x))) 3 | (define (cdar x) (cdr (car x))) 4 | (define (cddr x) (cdr (cdr x))) 5 | 6 | ; Some utility functions that you may find useful to implement 7 | 8 | (define (zip pairs) 9 | (list (map car pairs) (map cadr pairs)) 10 | ) 11 | 12 | 13 | ;; Problem 15 14 | ;; Returns a list of two-element lists 15 | (define (enumerate s) 16 | ; BEGIN PROBLEM 15 17 | (define (helper s i) 18 | (if (null? s) 19 | nil 20 | (cons (list i (car s)) 21 | (helper (cdr s) (+ i 1)) 22 | ) 23 | ) 24 | ) 25 | (helper s 0) 26 | ) 27 | ; END PROBLEM 15 28 | 29 | ;; Problem 16 30 | 31 | ;; Merge two lists LIST1 and LIST2 according to COMP and return 32 | ;; the merged lists. 33 | (define (merge comp list1 list2) 34 | ; BEGIN PROBLEM 16 35 | (cond 36 | ((null? list1) list2) 37 | ((null? list2) list1) 38 | ((comp (car list1) (car list2)) (cons (car list1) (merge comp (cdr list1) list2))) 39 | (else (cons (car list2) (merge comp list1 (cdr list2)))) 40 | ) 41 | ) 42 | ; END PROBLEM 16 43 | 44 | 45 | (merge < '(1 5 7 9) '(4 8 10)) 46 | ; expect (1 4 5 7 8 9 10) 47 | (merge > '(9 7 5 1) '(10 8 4 3)) 48 | ; expect (10 9 8 7 5 4 3 1) 49 | 50 | ;; Problem 17 51 | 52 | (define (nondecreaselist s) 53 | ; BEGIN PROBLEM 17 54 | (cond 55 | ((null? (cdr s)) (list s)) 56 | ((> (car s) (cadr s)) 57 | (cons (list (car s)) (nondecreaselist (cdr s)))) 58 | (else 59 | (cons (cons (car s) (car (nondecreaselist (cdr s)))) (cdr (nondecreaselist (cdr s))))) 60 | ) 61 | ) 62 | ; END PROBLEM 17 63 | 64 | ;; Problem EC 65 | ;; Returns a function that checks if an expression is the special form FORM 66 | (define (check-special form) 67 | (lambda (expr) (equal? form (car expr)))) 68 | 69 | (define lambda? (check-special 'lambda)) 70 | (define define? (check-special 'define)) 71 | (define quoted? (check-special 'quote)) 72 | (define let? (check-special 'let)) 73 | 74 | ;; Converts all let special forms in EXPR into equivalent forms using lambda 75 | ;; https://github.com/Awei0418/cs61a_2020_fall/blob/ff1df88bc1bc79fe44f19b566efe230fd58e4bf3/projects/scheme/questions.scm 76 | (define (let-to-lambda expr) 77 | (cond ((atom? expr) 78 | ; BEGIN PROBLEM EC 79 | expr 80 | ; END PROBLEM EC 81 | ) 82 | ((quoted? expr) 83 | ; BEGIN PROBLEM EC 84 | expr 85 | ; END PROBLEM EC 86 | ) 87 | ((or (lambda? expr) 88 | (define? expr)) 89 | (let ((form (car expr)) 90 | (params (cadr expr)) 91 | (body (cddr expr))) 92 | ; BEGIN PROBLEM EC 93 | (append (list form params) (map let-to-lambda body)) 94 | ; END PROBLEM EC 95 | )) 96 | ((let? expr) 97 | (let ((values (cadr expr)) 98 | (body (cddr expr))) 99 | ; BEGIN PROBLEM EC 100 | (define form (car (zip values))) 101 | (define params (map let-to-lambda (cadr (zip values)))) 102 | (define body (map let-to-lambda body)) 103 | (cons (append (list 'lambda form) body) params) 104 | ; END PROBLEM EC 105 | )) 106 | (else 107 | ; BEGIN PROBLEM EC 108 | (map let-to-lambda expr) 109 | ; END PROBLEM EC 110 | ))) 111 | -------------------------------------------------------------------------------- /study guide 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/study guide 1.pdf -------------------------------------------------------------------------------- /study guide 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/311zzb/cs61a_fall2020/0772c92760bf1a270fed1f37805db728dbe6e111/study guide 2.pdf --------------------------------------------------------------------------------