This repository has been archived by the owner on Nov 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Maxfield Wang
committed
Nov 3, 2022
1 parent
8d6569b
commit f9ed560
Showing
2,566 changed files
with
596,393 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"python.formatting.provider": "yapf", | ||
"python.analysis.typeCheckingMode":"off", | ||
"python.languageServer": "Pylance", | ||
"editor.wordWrapColumn": 80 | ||
} |
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
{ | ||
"name": "Homework 1", | ||
"endpoint": "cal/cs61a/fa20/hw01", | ||
"src": [ | ||
"hw01.py" | ||
], | ||
"tests": { | ||
"hw*.py": "doctest", | ||
"tests/*.py": "ok_test" | ||
}, | ||
"default_tests": [ | ||
"a_plus_abs_b", | ||
"two_of_three", | ||
"largest_factor", | ||
"with_if_function", | ||
"with_if_statement", | ||
"hailstone" | ||
], | ||
"protocols": [ | ||
"file_contents", | ||
"grading", | ||
"analytics", | ||
"backup" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,151 @@ | ||
import math | ||
from operator import add, sub | ||
|
||
|
||
def a_plus_abs_b(a, b): | ||
"""Return a+abs(b), but without calling abs. | ||
>>> a_plus_abs_b(2, 3) | ||
5 | ||
>>> a_plus_abs_b(2, -3) | ||
5 | ||
>>> # a check that you didn't change the return statement! | ||
>>> import inspect, re | ||
>>> re.findall(r'^\s*(return .*)', inspect.getsource(a_plus_abs_b), re.M) | ||
['return f(a, b)'] | ||
""" | ||
if b < 0: | ||
f = sub | ||
else: | ||
f = add | ||
return f(a, b) | ||
|
||
|
||
def two_of_three(x, y, z): | ||
"""Return a*a + b*b, where a and b are the two smallest members of the | ||
positive numbers x, y, and z. | ||
>>> two_of_three(1, 2, 3) | ||
5 | ||
>>> two_of_three(5, 3, 1) | ||
10 | ||
>>> two_of_three(10, 2, 8) | ||
68 | ||
>>> two_of_three(5, 5, 5) | ||
50 | ||
>>> # check that your code consists of nothing but an expression (this docstring) | ||
>>> # a return statement | ||
>>> import inspect, ast | ||
>>> [type(x).__name__ for x in ast.parse(inspect.getsource(two_of_three)).body[0].body] | ||
['Expr', 'Return'] | ||
""" | ||
return (x * x + y * y + z * z) - max(x * x, y * y, z * z) | ||
|
||
|
||
def largest_factor(n): | ||
"""Return the largest factor of n that is smaller than n. | ||
>>> largest_factor(15) # factors are 1, 3, 5 | ||
5 | ||
>>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40 | ||
40 | ||
>>> largest_factor(13) # factor is 1 since 13 is prime | ||
1 | ||
""" | ||
factor = 2 # skip 1 as it's absolutely one of the factors. | ||
|
||
while factor < n: | ||
if n % factor == 0: | ||
return n // factor | ||
|
||
factor += 1 | ||
|
||
return 1 if n <= factor else factor | ||
|
||
|
||
def if_function(condition, true_result, false_result): | ||
"""Return true_result if condition is a true value, and | ||
false_result otherwise. | ||
>>> if_function(True, 2, 3) | ||
2 | ||
>>> if_function(False, 2, 3) | ||
3 | ||
>>> if_function(3==2, 3+2, 3-2) | ||
1 | ||
>>> if_function(3>2, 3+2, 3-2) | ||
5 | ||
""" | ||
if condition: | ||
return true_result | ||
else: | ||
return false_result | ||
|
||
|
||
def with_if_statement(): | ||
""" | ||
>>> result = with_if_statement() | ||
47 | ||
>>> print(result) | ||
None | ||
""" | ||
if cond(): | ||
return true_func() | ||
else: | ||
return false_func() | ||
|
||
|
||
def with_if_function(): | ||
""" | ||
>>> result = with_if_function() | ||
42 | ||
47 | ||
>>> print(result) | ||
None | ||
""" | ||
return if_function(cond(), true_func(), false_func()) | ||
|
||
|
||
def cond(): | ||
return False | ||
|
||
|
||
def true_func(): | ||
print(42) | ||
|
||
|
||
def false_func(): | ||
print(47) | ||
|
||
|
||
def hailstone(n): | ||
"""Print the hailstone sequence starting at n and return its | ||
length. | ||
>>> a = hailstone(10) | ||
10 | ||
5 | ||
16 | ||
8 | ||
4 | ||
2 | ||
1 | ||
>>> a | ||
7 | ||
""" | ||
|
||
print(n) | ||
|
||
length = 1 | ||
|
||
while n != 1: | ||
if n % 2 == 0: | ||
n = n // 2 | ||
|
||
else: | ||
n = 3 * n + 1 | ||
|
||
print(n) | ||
length += 1 | ||
|
||
return length |
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
'num_eights-correct', (0, 66) | ||
'pingpong-correct', (512, 66) | ||
'missing_digits-correct', (1024, 66) | ||
'count_coins-correct', (1536, 66) | ||
'make_anonymous_factorial-correct', (2048, 66) |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
'num_eights-correct', (0, 66) | ||
'pingpong-correct', (512, 66) | ||
'missing_digits-correct', (1024, 66) | ||
'count_coins-correct', (1536, 66) | ||
'make_anonymous_factorial-correct', (2048, 66) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,177 @@ | ||
from ast import parse, NodeVisitor, Name | ||
|
||
_NAMES = { | ||
'Add': '+', | ||
'And': 'and', | ||
'Assert': 'assert', | ||
'Assign': '=', | ||
'AugAssign': 'op=', | ||
'BitAnd': '&', | ||
'BitOr': '|', | ||
'BitXor': '^', | ||
'Break': 'break', | ||
'Recursion': 'recursive call', | ||
'ClassDef': 'class', | ||
'Continue': 'continue', | ||
'Del': 'del', | ||
'Delete': 'delete', | ||
'Dict': '{...}', | ||
'DictComp': '{...}', | ||
'Div': '/', | ||
'Ellipsis': '...', | ||
'Eq': '==', | ||
'ExceptHandler': 'except', | ||
'ExtSlice': '[::]', | ||
'FloorDiv': '//', | ||
'For': 'for', | ||
'FunctionDef': 'def', | ||
'Filter': 'filter', | ||
'GeneratorExp': '(... for ...)', | ||
'Global': 'global', | ||
'Gt': '>', | ||
'GtE': '>=', | ||
'If': 'if', | ||
'IfExp': '...if...else...', | ||
'Import': 'import', | ||
'ImportFrom': 'from ... import ...', | ||
'In': 'in', | ||
'Index': '...[...]', | ||
'Invert': '~', | ||
'Is': 'is', | ||
'IsNot': 'is not ', | ||
'LShift': '<<', | ||
'Lambda': 'lambda', | ||
'List': '[...]', | ||
'ListComp': '[...for...]', | ||
'Lt': '<', | ||
'LtE': '<=', | ||
'Mod': '%', | ||
'Mult': '*', | ||
'Nonlocal': 'nonlocal', | ||
'Not': 'not', | ||
'NotEq': '!=', | ||
'NotIn': 'not in', | ||
'Or': 'or', | ||
'Pass': 'pass', | ||
'Pow': '**', | ||
'RShift': '>>', | ||
'Raise': 'raise', | ||
'Return': 'return', | ||
'Set': '{ ... } (set)', | ||
'SetComp': '{ ... for ... } (set)', | ||
'Slice': '[ : ]', | ||
'Starred': '', | ||
'Sub': '-', | ||
'Subscript': '[]', | ||
'Try': 'try', | ||
'Tuple': '(... , ... )', | ||
'UAdd': '+', | ||
'USub': '-', | ||
'While': 'while', | ||
'With': 'with', | ||
'Yield': 'yield', | ||
'YieldFrom': 'yield from', | ||
} | ||
|
||
def check(source_file, checked_funcs, disallow, source=None): | ||
"""Checks that AST nodes whose type names are present in DISALLOW | ||
(an object supporting 'in') are not present in the function(s) named | ||
CHECKED_FUNCS in SOURCE. By default, SOURCE is the contents of the | ||
file SOURCE_FILE. CHECKED_FUNCS is either a string (indicating a single | ||
name) or an object of some other type that supports 'in'. CHECKED_FUNCS | ||
may contain __main__ to indicate an entire module. Prints reports of | ||
each prohibited node and returns True iff none are found. | ||
See ast.__dir__() for AST type names. The special node name 'Recursion' | ||
checks for overtly recursive calls (i.e., calls of the form NAME(...) where | ||
NAME is an enclosing def.""" | ||
return ExclusionChecker(disallow).check(source_file, checked_funcs, source) | ||
|
||
class ExclusionChecker(NodeVisitor): | ||
"""An AST visitor that checks that certain constructs are excluded from | ||
parts of a program. ExclusionChecker(EXC) checks that AST node types | ||
whose names are in the sequence or set EXC are not present. Its check | ||
method visits nodes in a given function of a source file checking that the | ||
indicated node types are not used.""" | ||
|
||
def __init__(self, disallow=()): | ||
"""DISALLOW is the initial default list of disallowed | ||
node-type names.""" | ||
self._disallow = set(disallow) | ||
self._checking = False | ||
self._errs = 0 | ||
|
||
def generic_visit(self, node): | ||
if self._checking and type(node).__name__ in self._disallow: | ||
self._report(node) | ||
super().generic_visit(node) | ||
|
||
def visit_Module(self, node): | ||
if "__main__" in self._checked_funcs: | ||
self._checking = True | ||
self._checked_name = self._source_file | ||
super().generic_visit(node) | ||
|
||
def visit_Call(self, node): | ||
if 'Recursion' in self._disallow and \ | ||
type(node.func) is Name and \ | ||
node.func.id in self._func_nest: | ||
self._report(node, "should not be recursive") | ||
self.generic_visit(node) | ||
|
||
def visit_FunctionDef(self, node): | ||
self._func_nest.append(node.name) | ||
if self._checking: | ||
self.generic_visit(node) | ||
elif node.name in self._checked_funcs: | ||
self._checked_name = "Function " + node.name | ||
checking0 = self._checking | ||
self._checking = True | ||
super().generic_visit(node) | ||
self._checking = checking0 | ||
self._func_nest.pop() | ||
|
||
def _report(self, node, msg=None): | ||
node_name = _NAMES.get(type(node).__name__, type(node).__name__) | ||
if msg is None: | ||
msg = "should not contain '{}'".format(node_name) | ||
print("{} {}".format(self._checked_name, msg)) | ||
self._errs += 1 | ||
|
||
def errors(self): | ||
"""Returns the number of number of prohibited constructs found in | ||
the last call to check.""" | ||
return self._errs | ||
|
||
def check(self, source_file, checked_funcs, disallow=None, source=None): | ||
"""Checks that AST nodes whose type names are present in DISALLOW | ||
(an object supporting the contains test) are not present in | ||
the function(s) named CHECKED_FUNCS in SOURCE. By default, SOURCE | ||
is the contents of the file SOURCE_FILE. DISALLOW defaults to the | ||
argument given to the constructor (and resets that value if it is | ||
present). CHECKED_FUNCS is either a string (indicating a single | ||
name) or an object of some other type that supports 'in'. | ||
CHECKED_FUNCS may contain __main__ to indicate an entire module. | ||
Prints reports of each prohibited node and returns True iff none | ||
are found. | ||
See ast.__dir__() for AST type names. The special node name | ||
'Recursion' checks for overtly recursive calls (i.e., calls of the | ||
form NAME(...) where NAME is an enclosing def.""" | ||
|
||
self._checking = False | ||
self._source_file = source_file | ||
self._func_nest = [] | ||
if type(checked_funcs) is str: | ||
self._checked_funcs = { checked_funcs } | ||
else: | ||
self._checked_funcs = set(checked_funcs) | ||
if disallow is not None: | ||
self._disallow = set(disallow) | ||
if source is None: | ||
with open(source_file, 'r', errors='ignore') as inp: | ||
source = inp.read() | ||
p = parse(source, source_file) | ||
self._errs = 0 | ||
|
||
self.visit(p) | ||
return self._errs == 0 | ||
|
Oops, something went wrong.