Important:
Use recursion; the tests will fail if you use any assignment statements or loops.
-(You can, however, use function definitions if you'd like.)
+(You can define new functions, but don't put assignment statements there either.)
@@ -272,18 +272,14 @@
Q2: Digit Distance
consecutive digits. For example:
-
The digit distance of 6 is 0.
The digit distance of 61 is 5, as the absolute value of 6 - 1 is 5.
-
The digit distance of 71253 is 12 (6 + 1 + 3 + 2).
+
The digit distance of 71253 is 12 (abs(7-1) + abs(1-2) + abs(2-5) + abs(5-3) = 6 + 1 + 3 + 2).
+
The digit distance of 6 is 0 because there are no pairs of consecutive digits.
-
Write a function that determines the digit distance of a given positive integer.
+
Write a function that determines the digit distance of a positive integer.
You must use recursion or the tests will fail.
-
Hint: There are multiple valid ways of solving this problem!
-If you're stuck, try writing out an iterative solution
-first, and then convert your iterative solution into a recursive one.
Important: Implement this function without using any loops or directly testing if a number
-is odd or even -- aka modulos (%) are not allowed! Instead of directly checking whether a number
+is odd or even (no using %). Instead of directly checking whether a number
is even or odd, start with 1, which you know is an odd number.
Hint: Introduce an inner helper function that takes an odd number k and
@@ -392,7 +386,7 @@
Submit Assignment
Just For Fun Questions
-
The questions below are out of scope for 61A. You can try them if you want an extra challenge, but they're just puzzles that are not required for the course. Almost all students will skip them, and that's fine. We will not be prioritizing support for these questions on Ed or during Office Hours.
+
The questions below are optional and not representative of exam questions. You can try them if you want an extra challenge, but they're just puzzles that are not required for the course. Almost all students will skip them, and that's fine. We will not be prioritizing support for these questions on Ed or during office hours.
Q4: Towers of Hanoi
diff --git a/hw/hw05/construct_check.py b/hw/hw05/construct_check.py
deleted file mode 100644
index bee096e7e4..0000000000
--- a/hw/hw05/construct_check.py
+++ /dev/null
@@ -1,180 +0,0 @@
-from ast import parse, NodeVisitor, Name
-
-# For error messages (student-facing) only
-_NAMES = {
- 'Add': '+',
- 'And': 'and',
- 'Assert': 'assert',
- 'Assign': '=',
- 'AnnAssign': '=',
- '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': '*',
- 'NamedExpr': ':=',
- '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': '',
- 'Str': 'str',
- '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
\ No newline at end of file
diff --git a/hw/hw05/hw05.ok b/hw/hw05/hw05.ok
deleted file mode 100644
index 7563437b1c..0000000000
--- a/hw/hw05/hw05.ok
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "name": "Homework 5",
- "endpoint": "cal/cs61a/fa24/hw05",
- "src": [
- "hw05.py"
- ],
- "tests": {
- "hw*.py": "doctest",
- "tests/*.py": "ok_test"
- },
- "default_tests": [
- "hailstone",
- "merge",
- "yield_paths"
- ],
- "protocols": [
- "restore",
- "file_contents",
- "analytics",
- "help",
- "unlock",
- "grading",
- "backup"
- ]
-}
\ No newline at end of file
diff --git a/hw/hw05/hw05.py b/hw/hw05/hw05.py
deleted file mode 100644
index 02c48e0d06..0000000000
--- a/hw/hw05/hw05.py
+++ /dev/null
@@ -1,135 +0,0 @@
-def hailstone(n):
- """Q1: Yields the elements of the hailstone sequence starting at n.
- At the end of the sequence, yield 1 infinitely.
-
- >>> hail_gen = hailstone(10)
- >>> [next(hail_gen) for _ in range(10)]
- [10, 5, 16, 8, 4, 2, 1, 1, 1, 1]
- >>> next(hail_gen)
- 1
- """
- "*** YOUR CODE HERE ***"
-
-
-def merge(a, b):
- """Q2:
- >>> def sequence(start, step):
- ... while True:
- ... yield start
- ... start += step
- >>> a = sequence(2, 3) # 2, 5, 8, 11, 14, ...
- >>> b = sequence(3, 2) # 3, 5, 7, 9, 11, 13, 15, ...
- >>> result = merge(a, b) # 2, 3, 5, 7, 8, 9, 11, 13, 14, 15
- >>> [next(result) for _ in range(10)]
- [2, 3, 5, 7, 8, 9, 11, 13, 14, 15]
- """
- "*** YOUR CODE HERE ***"
-
-
-def yield_paths(t, value):
- """Q4: Yields all possible paths from the root of t to a node with the label
- value as a list.
-
- >>> t1 = tree(1, [tree(2, [tree(3), tree(4, [tree(6)]), tree(5)]), tree(5)])
- >>> print_tree(t1)
- 1
- 2
- 3
- 4
- 6
- 5
- 5
- >>> next(yield_paths(t1, 6))
- [1, 2, 4, 6]
- >>> path_to_5 = yield_paths(t1, 5)
- >>> sorted(list(path_to_5))
- [[1, 2, 5], [1, 5]]
-
- >>> t2 = tree(0, [tree(2, [t1])])
- >>> print_tree(t2)
- 0
- 2
- 1
- 2
- 3
- 4
- 6
- 5
- 5
- >>> path_to_2 = yield_paths(t2, 2)
- >>> sorted(list(path_to_2))
- [[0, 2], [0, 2, 1, 2]]
- """
- if label(t) == value:
- yield ____
- for b in branches(t):
- for ____ in ____:
- yield ____
-
-
-
-# Tree Data Abstraction
-
-def tree(label, branches=[]):
- """Construct a tree with the given label value and a list of branches."""
- for branch in branches:
- assert is_tree(branch), 'branches must be trees'
- return [label] + list(branches)
-
-def label(tree):
- """Return the label value of a tree."""
- return tree[0]
-
-def branches(tree):
- """Return the list of branches of the given tree."""
- return tree[1:]
-
-def is_tree(tree):
- """Returns True if the given tree is a tree, and False otherwise."""
- if type(tree) != list or len(tree) < 1:
- return False
- for branch in branches(tree):
- if not is_tree(branch):
- return False
- return True
-
-def is_leaf(tree):
- """Returns True if the given tree's list of branches is empty, and False
- otherwise.
- """
- return not branches(tree)
-
-def print_tree(t, indent=0):
- """Print a representation of this tree in which each node is
- indented by two spaces times its depth from the root.
-
- >>> print_tree(tree(1))
- 1
- >>> print_tree(tree(1, [tree(2)]))
- 1
- 2
- >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
- >>> print_tree(numbers)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- """
- print(' ' * indent + str(label(t)))
- for b in branches(t):
- print_tree(b, indent + 1)
-
-def copy_tree(t):
- """Returns a copy of t. Only for testing purposes.
-
- >>> t = tree(5)
- >>> copy = copy_tree(t)
- >>> t = tree(6)
- >>> print_tree(copy)
- 5
- """
- return tree(label(t), [copy_tree(b) for b in branches(t)])
-
diff --git a/hw/hw05/hw05.zip b/hw/hw05/hw05.zip
deleted file mode 100644
index 48fbd8e204..0000000000
Binary files a/hw/hw05/hw05.zip and /dev/null differ
diff --git a/hw/hw05/index.html b/hw/hw05/index.html
deleted file mode 100644
index f3bf96302b..0000000000
--- a/hw/hw05/index.html
+++ /dev/null
@@ -1,538 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Homework 5 | CS 61A Fall 2024
-
-
-
-
-
-
-
-
-
Download hw05.zip. Inside the archive, you will find a file called
-hw05.py, along with a copy of the ok autograder.
-
-
Submission: When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the
-final submission will be scored. Check that you have successfully submitted
-your code on Gradescope. See Lab 0 for more instructions on
-submitting assignments.
-
-
Using Ok: If you have any questions about using Ok, please
-refer to this guide.
-
-
-
Readings: You might find the following references
- useful:
Grading: Homework is graded based on
-correctness. Each incorrect problem will decrease the total score by one point.
-This homework is out of 2 points.
-
-
-
-
-
-
Required Questions
-
-
-
-
-
-
-
-
-
Getting Started Videos
-
-
-
These videos may provide some helpful direction for tackling the coding
-problems on this assignment.
-
-
To see these videos, you should be logged into your berkeley.edu email.
Write a generator function that yields the elements of the hailstone sequence starting at number n.
-After reaching the end of the hailstone sequence, the generator should yield the value 1 indefinitely.
-
-
Here's a quick reminder of how the hailstone sequence is defined:
-
-
-
Pick a positive integer n as the start.
-
If n is even, divide it by 2.
-
If n is odd, multiply it by 3 and add 1.
-
Continue this process until n is 1.
-
-
-
Try to write this generator function recursively. If you're stuck, you can first try writing it iteratively
-and then seeing how you can turn that implementation into a recursive one.
-
-
Hint: Since hailstone returns a generator, you can yield from a call to hailstone!
-
-
-
-
def hailstone(n):
- """Q1: Yields the elements of the hailstone sequence starting at n.
- At the end of the sequence, yield 1 infinitely.
-
- >>> hail_gen = hailstone(10)
- >>> [next(hail_gen) for _ in range(10)]
- [10, 5, 16, 8, 4, 2, 1, 1, 1, 1]
- >>> next(hail_gen)
- 1
- """
- "*** YOUR CODE HERE ***"
-
-
-
-
-
Use Ok to test your code:
python3 ok -q hailstone
-
-
-
-
-
Q2: Merge
-
-
Write a generator function merge that takes in two infinite generators a and b that are in increasing order without duplicates and returns a generator that has all the elements of both generators, in increasing order, without duplicates.
Define a generator function yield_paths which takes in a tree t, a value
-value, and returns a generator object which yields each path from the root
-of t to a node that has label value.
-
-
Each path should be represented as a list of the labels along that path in the
-tree. You may yield the paths in any order.
-
-
def yield_paths(t, value):
- """Q4: Yields all possible paths from the root of t to a node with the label
- value as a list.
-
- >>> t1 = tree(1, [tree(2, [tree(3), tree(4, [tree(6)]), tree(5)]), tree(5)])
- >>> print_tree(t1)
- 1
- 2
- 3
- 4
- 6
- 5
- 5
- >>> next(yield_paths(t1, 6))
- [1, 2, 4, 6]
- >>> path_to_5 = yield_paths(t1, 5)
- >>> sorted(list(path_to_5))
- [[1, 2, 5], [1, 5]]
-
- >>> t2 = tree(0, [tree(2, [t1])])
- >>> print_tree(t2)
- 0
- 2
- 1
- 2
- 3
- 4
- 6
- 5
- 5
- >>> path_to_2 = yield_paths(t2, 2)
- >>> sorted(list(path_to_2))
- [[0, 2], [0, 2, 1, 2]]
- """
- if label(t) == value:
- yield ____
- for b in branches(t):
- for ____ in ____:
- yield ____
-
-
-
Hint: If you're having trouble getting started, think about how you'd approach this
-problem if it wasn't a generator function. What would your recursive calls be?
-With a generator function, what happens if you make a "recursive call" within its body?
-
-
-
-
Hint: Try coming up with a few simple cases of your own! How should this function work when t is a leaf node?
-
-
-
-
Hint: Remember, it's possible to loop over generator objects because generators are iterators!
-
-
-
-
Note: Remember that this problem should yield paths -- do not return a list of paths!
-
-
-
-
Use Ok to test your code:
python3 ok -q yield_paths
-
-
-
-
-
-
-
Check Your Score Locally
-
-
You can locally check your score on each question of this assignment by running
-
-
python3 ok --score
-
-
This does NOT submit the assignment! When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it.
-
-
-
Submit Assignment
-
-
-
Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment.Lab 00 has detailed instructions.
-
-
-
Exam Practice
-
-
-
Homework assignments will also contain prior exam questions for you to try.
-These questions have no submission component; feel free to attempt them if you'd like some practice!
Download hw06.zip. Inside the archive, you will find a file called
-hw06.py, along with a copy of the ok autograder.
-
-
Submission: When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the
-final submission will be scored. Check that you have successfully submitted
-your code on Gradescope. See Lab 0 for more instructions on
-submitting assignments.
-
-
Using Ok: If you have any questions about using Ok, please
-refer to this guide.
-
-
-
-
Grading: Homework is graded based on
-correctness. Each incorrect problem will decrease the total score by one point.
-This homework is out of 2 points.
-
-
-
-
-
-
Required Questions
-
-
-
-
-
-
-
-
Getting Started Videos
-
-
-
These videos may provide some helpful direction for tackling the coding
-problems on this assignment.
-
-
To see these videos, you should be logged into your berkeley.edu email.
Confidentiality:
-Your responses to the survey are confidential, and only the instructors
-will be able to see this data unanonymized.
-More specifics on confidentiality can be found on the survey itself.
-
-
Once you finish the survey, you will be presented with a passphrase (if you miss
-it, it should also be at the bottom of the confirmation email you receive). Put
-this passphrase, as a string, on the line that says
-passphrase = 'REPLACE_THIS_WITH_PASSPHRASE' in the Python file for this assignment.
-E.g. if the passphrase is abc, then the line should be passphrase = 'abc'.
-
-
Use Ok to test your code:
python3 ok -q midsem_survey
-
-
-
-
-
OOP
-
-
-
Q2: Vending Machine
-
-
-
In this question you'll create a vending machine that sells a single product and provides change when needed.
-
-
Create a class called VendingMachine that represents a vending
-machine for some product. A VendingMachine object returns strings
-describing its interactions. Make sure your output exactly matches the strings in the doctests including punctuation and spacing!
-
-
You may find Python's formatted string literals, or f-strings useful.
-A quick example:
Fill in the VendingMachine class, adding attributes and methods as appropriate, such that its behavior matches the following doctests:
-
-
-
-
class VendingMachine:
- """A vending machine that vends some product for some price.
-
- >>> v = VendingMachine('candy', 10)
- >>> v.vend()
- 'Nothing left to vend. Please restock.'
- >>> v.add_funds(15)
- 'Nothing left to vend. Please restock. Here is your $15.'
- >>> v.restock(2)
- 'Current candy stock: 2'
- >>> v.vend()
- 'Please add $10 more funds.'
- >>> v.add_funds(7)
- 'Current balance: $7'
- >>> v.vend()
- 'Please add $3 more funds.'
- >>> v.add_funds(5)
- 'Current balance: $12'
- >>> v.vend()
- 'Here is your candy and $2 change.'
- >>> v.add_funds(10)
- 'Current balance: $10'
- >>> v.vend()
- 'Here is your candy.'
- >>> v.add_funds(15)
- 'Nothing left to vend. Please restock. Here is your $15.'
-
- >>> w = VendingMachine('soda', 2)
- >>> w.restock(3)
- 'Current soda stock: 3'
- >>> w.restock(3)
- 'Current soda stock: 6'
- >>> w.add_funds(2)
- 'Current balance: $2'
- >>> w.vend()
- 'Here is your soda.'
- """
- "*** YOUR CODE HERE ***"
-
-
-
-
-
Use Ok to test your code:
python3 ok -q VendingMachine
-
-
-
-
-
-
-
Check Your Score Locally
-
-
You can locally check your score on each question of this assignment by running
-
-
python3 ok --score
-
-
This does NOT submit the assignment! When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it.
-
-
Submit Assignment
-
-
-
Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment.Lab 00 has detailed instructions.
-
-
-
Optional Questions
-
-
-
Q3: Store Digits
-
-
-
Write a function store_digits that takes in an integer n and returns
-a linked list where each element of the list is a digit of n.
-
-
Important: Do not use any string manipulation functions like str and reversed.
-
-
-
-
def store_digits(n):
- """Stores the digits of a positive number n in a linked list.
-
- >>> s = store_digits(1)
- >>> s
- Link(1)
- >>> store_digits(2345)
- Link(2, Link(3, Link(4, Link(5))))
- >>> store_digits(876)
- Link(8, Link(7, Link(6)))
- >>> store_digits(2450)
- Link(2, Link(4, Link(5, Link(0))))
- >>> # a check for restricted functions
- >>> import inspect, re
- >>> cleaned = re.sub(r"#.*\\n", '', re.sub(r'"{3}[\s\S]*?"{3}', '', inspect.getsource(store_digits)))
- >>> print("Do not use str or reversed!") if any([r in cleaned for r in ["str", "reversed"]]) else None
- """
- "*** YOUR CODE HERE ***"
-
-
-
-
-
Use Ok to test your code:
python3 ok -q store_digits
-
-
-
-
-
Q4: Mutable Mapping
-
-
-
Implement deep_map_mut(func, link), which applies a function func onto
-all elements in the given linked list lnk. If an element is itself a
-linked list, apply func to each of its elements, and so on.
-
-
Your implementation should mutate the original linked list. Do not
-create any new linked lists.
-
-
Hint: The built-in isinstance function may be useful.
Construct Check: The last doctest of this question ensures that you
-do not create new linked lists. If you are failing this doctest, ensure
-that you are not creating link lists by calling the constructor, i.e.
-
-
s = Link(1)
-
-
-
-
def deep_map_mut(func, lnk):
- """Mutates a deep link lnk by replacing each item found with the
- result of calling func on the item. Does NOT create new Links (so
- no use of Link's constructor).
-
- Does not return the modified Link object.
-
- >>> link1 = Link(3, Link(Link(4), Link(5, Link(6))))
- >>> print(link1)
- <3 <4> 5 6>
- >>> # Disallow the use of making new Links before calling deep_map_mut
- >>> Link.__init__, hold = lambda *args: print("Do not create any new Links."), Link.__init__
- >>> try:
- ... deep_map_mut(lambda x: x * x, link1)
- ... finally:
- ... Link.__init__ = hold
- >>> print(link1)
- <9 <16> 25 36>
- """
- "*** YOUR CODE HERE ***"
-
-
-
-
-
Use Ok to test your code:
python3 ok -q deep_map_mut
-
-
-
-
-
Q5: Two List
-
-
-
Implement a function two_list that takes in two lists and returns a linked list. The first list contains the
-values that we want to put in the linked list, and the second list contains the number of each corresponding value.
-Assume both lists are the same size and have a length of 1 or greater. Assume all elements in the second list
-are greater than 0.
-
-
-
-
def two_list(vals, counts):
- """
- Returns a linked list according to the two lists that were passed in. Assume
- vals and counts are the same size. Elements in vals represent the value, and the
- corresponding element in counts represents the number of this value desired in the
- final linked list. Assume all elements in counts are greater than 0. Assume both
- lists have at least one element.
- >>> a = [1, 3]
- >>> b = [1, 1]
- >>> c = two_list(a, b)
- >>> c
- Link(1, Link(3))
- >>> a = [1, 3, 2]
- >>> b = [2, 2, 1]
- >>> c = two_list(a, b)
- >>> c
- Link(1, Link(1, Link(3, Link(3, Link(2)))))
- """
- "*** YOUR CODE HERE ***"
-
-
-
-
-
Use Ok to test your code:
python3 ok -q two_list
-
-
-
-
-
Exam Practice
-
-
Homework assignments will also contain prior exam questions for you to try.
-These questions have no submission component; feel free to attempt them if you'd like some practice!
Download hw07.zip. Inside the archive, you will find a file called
-hw07.scm, along with a copy of the ok autograder.
-
-
Submission: When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the
-final submission will be scored. Check that you have successfully submitted
-your code on Gradescope. See Lab 0 for more instructions on
-submitting assignments.
-
-
Using Ok: If you have any questions about using Ok, please
-refer to this guide.
-
-
-
Readings: You might find the following references
- useful:
Grading: Homework is graded based on
-correctness. Each incorrect problem will decrease the total score by one point.
-This homework is out of 2 points.
-
-
-
-
-
-
The 61A Scheme interpreter is included in each Scheme assignment. To start it,
-type python3 scheme in a terminal. To load a Scheme file called f.scm, type python3 scheme -i f.scm. To exit the Scheme interpreter, type
-(exit).
-
-
Scheme Editor
-
-
-
All Scheme assignments include a web-based editor that makes it easy to run ok
-tests and visualize environments. Type python3 editor in a terminal, and the
-editor will open in a browser window (at http://127.0.0.1:31415/). Whatever
-changes you make here will also save to the original file on your computer!
-To stop running the editor and return to the command line, type Ctrl-C in the
-terminal where you started the editor.
-
-
The Run button loads the current assignment's .scm file and opens a Scheme
-interpreter, allowing you to try evaluating different Scheme expressions.
-
-
The Test button runs all ok tests for the assignment. Click View Case for a
-failed test, then click Debug to step through its evaluation.
-
-
Recommended VS Code Extensions
-
-
-
If you choose to use VS Code as your text editor (instead of the web-based editor),
-install the vscode-scheme
-extension so that parentheses are highlighted.
-
-
Before:
-
-
-
-
After:
-
-
-
-
In addition, the 61a-bot (installation instructions) VS Code extension is available for Scheme homeworks. The bot is also integrated into ok.
-
-
-
Required Questions
-
-
-
-
-
-
-
-
Getting Started Videos
-
-
-
These videos may provide some helpful direction for tackling the coding
-problems on this assignment.
-
-
To see these videos, you should be logged into your berkeley.edu email.
Implement a procedure pow that raises a base to the power of a nonnegative integer exp. The number of recursive pow calls should grow logarithmically with respect to exp, rather than linearly. For example, (pow 2 32) should result in 5 recursive pow calls rather than 32 recursive pow calls.
-
-
Hint:
-
-
-
x2y = (xy)2
-
x2y+1 = x(xy)2
-
-
-
For example, 216 = (28)2 and 217 = 2 * (28)2.
-
-
You may use the built-in predicates even? and odd?. Also, the square procedure is defined for you.
-
-
Scheme doesn't have while or for statements, so use recursion to solve this problem.
-
-
-
-
(define (square n) (* n n))
-
-(define (pow base exp)
- 'YOUR-CODE-HERE
-)
-
-
-
-
-
Use Ok to test your code:
python3 ok -q pow
-
-
-
-
-
-
-
Q2: Repeatedly Cube
-
-
-
Implement repeatedly-cube, which receives a number x and cubes it n times.
-
-
Here are some examples of how repeatedly-cube should behave:
-
-
scm> (repeatedly-cube 100 1) ; 1 cubed 100 times is still 1
-1
-scm> (repeatedly-cube 2 2) ; (2^3)^3
-512
-scm> (repeatedly-cube 3 2) ; ((2^3)^3)^3
-134217728
Download hw08.zip. Inside the archive, you will find a file called
-hw08.scm, along with a copy of the ok autograder.
-
-
Submission: When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the
-final submission will be scored. Check that you have successfully submitted
-your code on Gradescope. See Lab 0 for more instructions on
-submitting assignments.
-
-
Using Ok: If you have any questions about using Ok, please
-refer to this guide.
-
-
-
Readings: You might find the following references
- useful:
Grading: Homework is graded based on
-correctness. Each incorrect problem will decrease the total score by one point.
-This homework is out of 2 points.
-
-
-
-
-
-
The 61A Scheme interpreter is included in each Scheme assignment. To start it,
-type python3 scheme in a terminal. To load a Scheme file called f.scm, type python3 scheme -i f.scm. To exit the Scheme interpreter, type
-(exit).
-
-
Scheme Editor
-
-
-
All Scheme assignments include a web-based editor that makes it easy to run ok
-tests and visualize environments. Type python3 editor in a terminal, and the
-editor will open in a browser window (at http://127.0.0.1:31415/). Whatever
-changes you make here will also save to the original file on your computer!
-To stop running the editor and return to the command line, type Ctrl-C in the
-terminal where you started the editor.
-
-
The Run button loads the current assignment's .scm file and opens a Scheme
-interpreter, allowing you to try evaluating different Scheme expressions.
-
-
The Test button runs all ok tests for the assignment. Click View Case for a
-failed test, then click Debug to step through its evaluation.
-
-
Recommended VS Code Extensions
-
-
-
If you choose to use VS Code as your text editor (instead of the web-based editor),
-install the vscode-scheme
-extension so that parentheses are highlighted.
-
-
Before:
-
-
-
-
After:
-
-
-
-
In addition, the 61a-bot (installation instructions) VS Code extension is available for Scheme homeworks. The bot is also integrated into ok.
-
-
-
Required Questions
-
-
-
-
Required Questions
-
-
-
-
-
-
-
-
Getting Started Videos
-
-
-
These videos may provide some helpful direction for tackling the coding
-problems on this assignment.
-
-
To see these videos, you should be logged into your berkeley.edu email.
Implement a procedure called ascending?, which takes a list of numbers s and
-returns True if the numbers are in non-descending order, and False
-otherwise.
-
-
A list of numbers is non-descending if each element after the first is
-greater than or equal to the previous element. For example...
-
-
-
(1 2 3 3 4) is non-descending.
-
(1 2 3 3 2) is not.
-
-
-
Hint: The built-in null? procedure returns whether its argument is nil.
-
-
-
-
Note: The question mark in ascending? is just part of the procedure name and has no special meaning in terms of Scheme syntax. It is a common practice in Scheme to name procedures with a question mark at the end if it returns a boolean value.
-
-
(define (ascending? s)
- 'YOUR-CODE-HERE
-)
-
-
-
-
-
-
Use Ok to unlock and test your code:
python3 ok -q ascending -u
-python3 ok -q ascending
-
-
-
-
-
-
Q2: My Filter
-
-
-
Write a procedure my-filter, which takes a predicate pred and a list s, and
-returns a new list containing only elements of the list that satisfy the
-predicate. The output should contain the elements in the same order that they
-appeared in the original list.
-
-
Note: Make sure that you are not just calling the built-in filter function in Scheme - we are asking you to re-implement this!
-
-
-
-
(define (my-filter pred s)
- 'YOUR-CODE-HERE
-)
-
-
-
-
-
-
-
Use Ok to unlock and test your code:
python3 ok -q filter -u
-python3 ok -q filter
-
-
-
-
-
-
Q3: Interleave
-
-
-
Implement the function interleave, which takes two lists lst1 and lst2 as
-arguments. interleave should return a list that interleaves the elements
-of the two lists. (In other words, the resulting list should contain elements
-alternating between lst1 and lst2, starting at lst1).
-
-
If one of the input lists to interleave is shorter than the other, then
-interleave should alternate elements from both lists until one list has no
-more elements, and then the remaining elements from the longer list should be
-added to the end of the new list. If lst1 is empty, you may simply return
-lst2 and vice versa.
python3 ok -q interleave -u
-python3 ok -q interleave
-
-
-
-
-
Q4: No Repeats
-
-
-
Implement no-repeats, which takes a list of numbers s. It returns a list
-that has all of the unique elements of s in the order that they first appear,
-but no repeats.
-
-
For example, (no-repeats (list 5 4 5 4 2 2)) evaluates to (5 4 2).
-
-
Hint: You may find it helpful to use filter with a lambda procedure to
-filter out repeats. To test if two numbers a and b are not equal, use
-(not (= a b)).
-
-
-
-
(define (no-repeats s)
- 'YOUR-CODE-HERE
-)
-
-
-
-
-
-
-
Use Ok to test your code:
python3 ok -q no_repeats
-
-
-
-
-
Submit Assignment
-
-
-
Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment.Lab 00 has detailed instructions.
-
-
-
Exam Practice
-
-
The following are some Scheme List exam problems from previous semesters that you may find useful as additional exam practice.
Download hw09.zip. Inside the archive, you will find a file called
-hw09.scm, along with a copy of the ok autograder.
-
-
Submission: When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the
-final submission will be scored. Check that you have successfully submitted
-your code on Gradescope. See Lab 0 for more instructions on
-submitting assignments.
-
-
Using Ok: If you have any questions about using Ok, please
-refer to this guide.
-
-
-
Readings: You might find the following references
- useful:
Grading: Homework is graded based on
-correctness. Each incorrect problem will decrease the total score by one point.
-This homework is out of 2 points.
-
-
-
-
-
-
The 61A Scheme interpreter is included in each Scheme assignment. To start it,
-type python3 scheme in a terminal. To load a Scheme file called f.scm, type python3 scheme -i f.scm. To exit the Scheme interpreter, type
-(exit).
-
-
Scheme Editor
-
-
-
All Scheme assignments include a web-based editor that makes it easy to run ok
-tests and visualize environments. Type python3 editor in a terminal, and the
-editor will open in a browser window (at http://127.0.0.1:31415/). Whatever
-changes you make here will also save to the original file on your computer!
-To stop running the editor and return to the command line, type Ctrl-C in the
-terminal where you started the editor.
-
-
The Run button loads the current assignment's .scm file and opens a Scheme
-interpreter, allowing you to try evaluating different Scheme expressions.
-
-
The Test button runs all ok tests for the assignment. Click View Case for a
-failed test, then click Debug to step through its evaluation.
-
-
Recommended VS Code Extensions
-
-
-
If you choose to use VS Code as your text editor (instead of the web-based editor),
-install the vscode-scheme
-extension so that parentheses are highlighted.
-
-
Before:
-
-
-
-
After:
-
-
-
-
In addition, the 61a-bot (installation instructions) VS Code extension is available for Scheme homeworks. The bot is also integrated into ok.
-
-
-
Required Questions
-
-
-
-
-
-
-
-
-
Getting Started Videos
-
-
-
These videos may provide some helpful direction for tackling the coding
-problems on this assignment.
-
-
To see these videos, you should be logged into your berkeley.edu email.
Recall that currying transforms a multiple argument function into a series of higher-order, one argument functions. In the next set of questions, you will be creating functions that can automatically curry a function of any length using the notion that programs are data!
-
-
-
Q1: Cooking Curry
-
-
-
Implement the function curry-cook, which takes in a Scheme list formals and a quoted expression body. curry-cook should generate a program as a list which is a curried version of a lambda function. The outputted program should be a curried version of a lambda function with formal arguments equal to formals, and a function body equal to body. You may assume that all functions passed in will have more than 0 formals; otherwise, it would not be curry-able!
-
-
For example, if you wanted to curry the function (lambda (x y) (+ x y)), you would set formals equal to '(x y), the body equal to '(+ x y), and make a call to curry-cook: (curry-cook '(x y) '(+ x y)).
-
-
scm> (curry-cook '(a) 'a)
-(lambda (a) a)
-scm> (curry-cook '(x y) '(+ x y))
-(lambda (x) (lambda (y) (+ x y)))
Implement the function curry-consume, which takes in a curried lambda function curry and applies the function to a list of arguments args. You may make the following assumptions:
-
-
-
If curry is an n-curried function, then there will be at most n arguments in args.
-
If there are 0 arguments (args is an empty list), then you may assume that curry has been fully applied with relevant arguments; in this case, curry now contains a value representing the output of the lambda function. Return it.
-
-
-
Note that there can be fewer args than formals for the corresponding lambda function curry! In the case that there are fewer arguments, curry-consume should return a curried lambda function, which is the result of partially applying curry up to the number of args provdied. See the doctests below for a few examples.
-
-
scm> (define three-curry (lambda (x) (lambda (y) (lambda (z) (+ x (* y z)))) ))
-three-curry
-scm> (define eat-two (curry-consume three-curry '(1 2))) ; pass in only two arguments, return should be a one-arg lambda function!
-eat-two
-scm> eat-two
-(lambda (z) (+ x (* y z)))
-scm> (eat-two 3) ; pass in the last argument; 1 + (2 * 3)
-7
-scm> (curry-consume three-curry '(1 2 3)) ; all three arguments at once
-7
switch is a macro that takes in an expression expr and a list of pairs, options, where the first element of each pair is some value and the second element is a single expression. switch evaluates the expression contained in the list of options that corresponds to the value that expr evaluates to.
-
-
scm> (switch (+ 1 1) ((1 (print 'a))
- (2 (print 'b)) ; (print 'b) is evaluated because (+ 1 1) evaluates to 2
- (3 (print 'c))))
-b
-
-
-
-
switch uses another procedure called switch-to-cond in its implementation:
Your task is to define switch-to-cond, which is a procedure (not a macro) that takes a quoted switch expression and converts it into a cond expression with the same behavior. An example is shown below.
You can locally check your score on each question of this assignment by running
-
-
python3 ok --score
-
-
This does NOT submit the assignment! When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it.
-
-
Submit Assignment
-
-
-
Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment.Lab 00 has detailed instructions.
-
-
-
Exam Practice
-
-
-
Homework assignments will also contain prior exam questions for you to try.
-These questions have no submission component; feel free to attempt them if you'd like some practice!
Submission: When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the
-final submission will be scored. Check that you have successfully submitted
-your code on Gradescope. See Lab 0 for more instructions on
-submitting assignments.
-
-
Using Ok: If you have any questions about using Ok, please
-refer to this guide.
-
-
-
-
Grading: Homework is graded based on
-correctness. Each incorrect problem will decrease the total score by one point.
-This homework is out of 2 points.
-
-
-
-
-
-
-
-
To check your progress, you can run sqlite3 directly by running:
-
-
python3 sqlite_shell.py --init hw10.sql
-
-
You should also check your work using ok:
-
-
python3 ok
-
-
-
Required Questions
-
-
-
-
-
-
-
-
-
-
-
Getting Started Videos
-
-
-
These videos may provide some helpful direction for tackling the coding
-problems on this assignment.
-
-
To see these videos, you should be logged into your berkeley.edu email.
In each question below, you will define a new table based on the following
-tables.
-
-
CREATE TABLE parents AS
- SELECT "abraham" AS parent, "barack" AS child UNION
- SELECT "abraham" , "clinton" UNION
- SELECT "delano" , "herbert" UNION
- SELECT "fillmore" , "abraham" UNION
- SELECT "fillmore" , "delano" UNION
- SELECT "fillmore" , "grover" UNION
- SELECT "eisenhower" , "fillmore";
-
-CREATE TABLE dogs AS
- SELECT "abraham" AS name, "long" AS fur, 26 AS height UNION
- SELECT "barack" , "short" , 52 UNION
- SELECT "clinton" , "long" , 47 UNION
- SELECT "delano" , "long" , 46 UNION
- SELECT "eisenhower" , "short" , 35 UNION
- SELECT "fillmore" , "curly" , 32 UNION
- SELECT "grover" , "short" , 28 UNION
- SELECT "herbert" , "curly" , 31;
-
-CREATE TABLE sizes AS
- SELECT "toy" AS size, 24 AS min, 28 AS max UNION
- SELECT "mini" , 28 , 35 UNION
- SELECT "medium" , 35 , 45 UNION
- SELECT "standard" , 45 , 60;
-
-
Your tables should still perform correctly even if the values in these tables
-change. For example, if you are asked to list all dogs with a name that starts
-with h, you should write:
-
-
SELECT name FROM dogs WHERE "h" <= name AND name < "i";
-
-
Instead of assuming that the dogs table has only the data above and writing
-
-
SELECT "herbert";
-
-
The former query would still be correct if the name grover were changed to
-hoover or a row was added with the name harry.
-
-
-
Q1: By Parent Height
-
-
Create a table by_parent_height that has a column of the names of all dogs that have
-a parent, ordered by the height of the parent dog from tallest parent to shortest
-parent.
-
-
-- All dogs with parents ordered by decreasing height of their parent
-CREATE TABLE by_parent_height AS
- SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
-
-
-
For example, fillmore has a parent eisenhower with height 35, and so
-should appear before grover who has a parent fillmore with height 32.
-The names of dogs with parents of the same height should appear together in any
-order. For example, barack and clinton should both appear at the end, but
-either one can come before the other.
The Fédération Cynologique Internationale classifies a standard poodle as over
-45 cm and up to 60 cm. The sizes table describes this and other such
-classifications, where a dog must be over the min and less than or equal to
-the max in height to qualify as size.
-
-
Create a size_of_dogs table with two columns, one for each dog's name and
-another for its size.
-
-
-- The size of each dog
-CREATE TABLE size_of_dogs AS
- SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
-
There are two pairs of siblings that have the same size. Create a table that
-contains a row with a string for each of these pairs. Each string should be a
-sentence describing the siblings by their size.
-
-
-- Filling out this helper table is optional
-CREATE TABLE siblings AS
- SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
-
--- Sentences about siblings that are the same size
-CREATE TABLE sentences AS
- SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
-
-
-
Each sibling pair should appear only once in the output, and siblings should be
-listed in alphabetical order (e.g. "barack and clinton..." instead of
-"clinton and barack..."), as follows:
-
-
sqlite> SELECT * FROM sentences;
-The two siblings, barack and clinton, have the same size: standard
-The two siblings, abraham and grover, have the same size: toy
-
-
Hint: First, create a helper table containing each pair of siblings. This
-will make comparing the sizes of siblings when constructing the main table
-easier.
-
-
Hint: If you join a table with itself, use AS within the FROM clause to
-give each table an alias.
-
-
Hint: In order to concatenate two strings into one, use the || operator.
-
-
-
-
Use Ok to test your code:
python3 ok -q sentences
-
-
-
-
-
-
-
Q4: Low Variance
-
-
-
We want to create a table that contains the height range (difference between maximum and minimum height) of all dogs that share a fur type. However, we'll only
-consider fur types where each dog with that fur type is within 30% of the average height of all dogs with that fur type.
-
-
For example, if the average height for short-haired dogs is 10, then in order to be included in our
-output, all dogs with short hair must have a height of at most 13 and at least 7.
-
-
To achieve this, we can use MIN, MAX, and AVG.
-For this problem, we'll want to find the average height and make sure that:
-
-
-
There are no heights smaller than 0.7 of the average.
-
There are no heights greater than 1.3 of the average.
-
-
-
Your output should first include the fur type and then the height range for the fur types that meet
-this criteria.
-
-
-- Height range for each fur type where all of the heights differ by no more than 30% from the average height
-CREATE TABLE low_variance AS
- SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
-
--- Example:
-SELECT * FROM low_variance;
--- Expected output:
--- curly|1
-
-
Explanation: The average height of long-haired dogs is 39.7, so the low variance criterion requires the height of each long-haired dog to be between 27.8 and 51.6. However, abraham is a long-haired dog with height 26, which is outside this range. For short-haired dogs, barack falls outside the valid range (check!). Thus, neither short nor long haired dogs are included in the output. There are two curly haired dogs: fillmore with height 32 and herbert with height 31. This gives a height range of 1.
-
-
Use Ok to test your code:
python3 ok -q low_variance
-
-
-
-
-
Submit Assignment
-
-
-
Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment.Lab 00 has detailed instructions.
-
-
Make sure to submit hw10.sql to the autograder!
-
-
-
Exam Practice
-
-
-
The following are some SQL exam problems from previous semesters that you may find useful as additional exam practice.
If 80% or more students (computed as the fraction of the number of students who took Midterm 2)
-complete all three, then all students who complete this homework get an extra credit point!
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/hw/hw11/ok b/hw/hw11/ok
deleted file mode 100644
index 0d2fead7a3..0000000000
Binary files a/hw/hw11/ok and /dev/null differ
diff --git a/index.html b/index.html
index 68c4fd126a..9ff7e06ec9 100644
--- a/index.html
+++ b/index.html
@@ -506,13 +506,17 @@
Consult this section if you need a refresher on the material for this lab. It's
+okay to skip directly to the questions and refer back
+here should you get stuck.
+
+
+
+
+
+
+
Short Circuiting
+
+
+
What do you think will happen if we type the following into Python?
+
+
1 / 0
+
+
Try it out in Python! You should see a ZeroDivisionError. But what about this expression?
+
+
True or 1 / 0
+
+
It evaluates to True because Python's and and or operators short-circuit. That is, they don't necessarily evaluate every operand.
+
+
+
+
+
Operator
+
Checks if:
+
Evaluates from left to right up to:
+
Example
+
+
+
AND
+
All values are true
+
The first false value
+
False and 1 / 0 evaluates to False
+
+
+
OR
+
At least one value is true
+
The first true value
+
True or 1 / 0 evaluates to True
+
+
+
+
+
Short-circuiting happens when the operator reaches an operand that allows them to make a conclusion about the expression. For example, and will short-circuit as soon as it reaches the first false value because it then knows that not all the values are true.
+
+
If and and or do not short-circuit, they just return the last
+value; another way to remember this is that and and or always return the last
+thing they evaluate, whether they short circuit or not. Keep in mind that and and or
+don't always return booleans when using values other than True and False.
+
+
+
+
+
+
+
+
+
Higher-Order Functions
+
+
+
Variables are names bound to values, which can be primitives like 3 or
+'Hello World', but they can also be functions. And since functions can take
+arguments of any value, other functions can be passed in as arguments. This is
+the basis for higher-order functions.
+
+
A higher order function is a function that manipulates other functions by
+taking in functions as arguments, returning a function, or both. We will
+introduce the basics of higher order functions in this lab and will be
+exploring many applications of higher order functions in our next lab.
+
+
+
Functions as arguments
+
+
+
In Python, function objects are values that can be passed around. We know that one
+way to create functions is by using a def statement:
+
+
def square(x):
+ return x * x
+
+
The above statement created a function object with the intrinsic name square as
+well as binded it to the name square in the current environment. Now let's try
+passing it as an argument.
+
+
First, let's write a function that takes in another function as an argument:
+
+
def scale(f, x, k):
+ """ Returns the result of f(x) scaled by k. """
+ return k * f(x)
+
+
We can now call scale on square and some other arguments:
Note that in the body of the call to scale, the function object with the intrinsic
+name square is bound to the parameter f. Then, we call square in the body of
+scale by calling f(x).
+
+
As we saw in the above section on lambda expressions, we can also pass
+lambda expressions into call expressions!
+
+
>>> scale(lambda x: x + 10, 5, 2)
+30
+
+
In the frame for this call expression, the name f is bound to the function
+created by the lambda expression lambda x: x + 10.
+
+
+
Functions that return functions
+
+
+
Because functions are values, they are valid as return values! Here's an example:
+
+
def multiply_by(m):
+ def multiply(n):
+ return n * m
+ return multiply
+
+
In this particular case, we defined the function multiply within the body of multiply_by
+and then returned it. Let's see it in action:
+
+
>>> multiply_by(3)
+<function multiply_by.<locals>.multiply at ...>
+>>> multiply(4)
+Traceback (most recent call last):
+File "<stdin>", line 1, in <module>
+NameError: name 'multiply' is not defined
+
+
A call to multiply_by returns a function, as expected. However, calling
+multiply errors, even though that's the name we gave the inner function. This
+is because the name multiply only exists within the frame where we evaluate
+the body of multiply_by.
+
+
So how do we actually use the inner function? Here are two ways:
+
+
>>> times_three = multiply_by(3) # Assign the result of the call expression to a name
+>>> times_three(5) # Call the inner function with its new name
+15
+>>> multiply_by(3)(10) # Chain together two call expressions
+30
+
+
The point is, because multiply_by returns a function, you can use its return
+value just like you would use any other function.
+
+
+
+
+
+
+
+
+
+
+
+
Lambda Expressions
+
+
+
Lambda expressions are expressions that evaluate to functions by specifying two
+things: the parameters and a return expression.
+
+
lambda <parameters>: <return expression>
+
+
While both lambda expressions and def statements create function objects,
+there are some notable differences. lambda expressions work like other
+expressions; much like a mathematical expression just evaluates to a number and
+does not alter the current environment, a lambda expression
+evaluates to a function without changing the current environment. Let's take a
+closer look.
+
+
+
+
+
+
lambda
+
def
+
+
+
Type
+
Expression that evaluates to a value
+
Statement that alters the environment
+
+
+
Result of execution
+
Creates an anonymous lambda function with no intrinsic name.
+
Creates a function with an intrinsic name and binds it to that
+ name in the current environment.
+
+
+
Effect on the environment
+
Evaluating a lambda expression does not create or
+ modify any variables.
+
Executing a def statement both creates a new function
+ object and binds it to a name in the current environment.
+
+
+
Usage
+
A lambda expression can be used anywhere that
+ expects an expression, such as in an assignment statement or as the
+ operator or operand to a call expression.
+
After executing a def statement, the created
+ function is bound to a name. You should use this name to refer to the
+ function anywhere that expects an expression.
+
+
+
Example
+
+
# A lambda expression by itself does not alter
+# the environment
+lambda x: x * x
+
+# We can assign lambda functions to a name
+# with an assignment statement
+square = lambda x: x * x
+square(3)
+
+# Lambda expressions can be used as an operator
+# or operand
+negate = lambda f, x: -f(x)
+negate(lambda x: x * x, 3)
+
def square(x):
+ return x * x
+
+# A function created by a def statement
+# can be referred to by its intrinsic name
+square(3)
Environment diagrams are one of the best learning tools for understanding
+lambda expressions and higher order functions because you're able to keep
+track of all the different names, function objects, and arguments to functions.
+We highly recommend drawing environment diagrams or using Python
+tutor if you get stuck doing the WWPD problems below.
+For examples of what environment diagrams should look like, try running some
+code in Python tutor. Here are the rules:
+
+
+
Assignment Statements
+
+
+
+
Evaluate the expression on the right hand side of the = sign.
+
If the name found on the left hand side of the = doesn't already exist in
+ the current frame, write it in. If it does, erase the current binding. Bind the
+ value obtained in step 1 to this name.
+
+
+
If there is more than one name/expression in the statement, evaluate all the
+expressions first from left to right before making any bindings.
+
+
+
+
+
def Statements
+
+
+
+
Draw the function object with its intrinsic name, formal parameters, and
+ parent frame. A function's parent frame is the frame in which the function was
+ defined.
+
If the intrinsic name of the function doesn't already exist in the current
+ frame, write it in. If it does, erase the current binding. Bind the newly
+ created function object to this name.
+
+
+
+
+
+
Call expressions
+
+
+
Note: you do not have to go through this process for a built-in Python function like max or print.
+
+
+
Evaluate the operator, whose value should be a function.
+
Evaluate the operands left to right.
+
Open a new frame. Label it with the sequential frame number, the intrinsic
+ name of the function, and its parent.
+
Bind the formal parameters of the function to the arguments whose values you
+ found in step 2.
+
Execute the body of the function in the new environment.
+
+
+
+
+
+
Lambdas
+
+
+
Note: As we saw in the lambda expression section above, lambda
+functions have no intrinsic name. When drawing lambda functions in
+environment diagrams, they are labeled with the name lambda or with the
+lowercase Greek letter λ. This can get confusing when there are
+multiple lambda functions in an environment diagram, so you can distinguish
+them by numbering them or by writing the line number on which they were defined.
+
+
+
Draw the lambda function object and label it with λ, its formal
+ parameters, and its parent frame. A function's parent frame is the frame in
+ which the function was defined.
+
+
+
This is the only step. We are including this section to emphasize the fact that
+the difference between lambda expressions and def statements is that
+lambda expressions do not create any new bindings in the environment.
Important:
+For all WWPD questions, type Function if you believe the answer is
+<function...>, Error if it errors, and Nothing if nothing is displayed.
+
+
+
Q1: WWPD: Higher-Order Functions
+
+
+
Use Ok to test your knowledge with the following "What Would Python Display?" questions:
+>>> def snake(x, y):
+... if cake == more_cake:
+... return chocolate
+... else:
+... return x + y
+>>> snake(10, 20)
+
______
Function
+>>> snake(10, 20)()
+
______
30
+>>> cake = 'cake'
+>>> snake(10, 20)
+
______
30
+
+
+
+
+
Coding Practice
+
+
+
+
Q2: Composite Identity Function
+
+
+
Write a function that takes in two single-argument functions, f and g, and
+returns another function that has a single parameter x. The returned
+function should return True if f(g(x)) is equal to g(f(x)) and False
+otherwise. You can assume the output of g(x) is a valid input for f and vice
+versa.
+
+
+
+
def composite_identity(f, g):
+ """
+ Return a function with one parameter x that returns True if f(g(x)) is
+ equal to g(f(x)). You can assume the result of g(x) is a valid input for f
+ and vice versa.
+
+ >>> add_one = lambda x: x + 1 # adds one to x
+ >>> square = lambda x: x**2 # squares x [returns x^2]
+ >>> b1 = composite_identity(square, add_one)
+ >>> b1(0) # (0 + 1) ** 2 == 0 ** 2 + 1
+ True
+ >>> b1(4) # (4 + 1) ** 2 != 4 ** 2 + 1
+ False
+ """
+
+We must create a function to take x using lambda or def, then compare the two quantities.
+
+
+
Use Ok to test your code:
python3 ok -q composite_identity
+
+
+
+
+
Q3: Count Cond
+
+
+
Consider the following implementations of count_fives and count_primes which
+use the sum_digits and is_prime functions from earlier assignments:
+
+
def count_fives(n):
+ """Return the number of values i from 1 to n (including n)
+ where sum_digits(n * i) is 5.
+ >>> count_fives(10) # Among 10, 20, 30, ..., 100, only 50 (10 * 5) has digit sum 5
+ 1
+ >>> count_fives(50) # 50 (50 * 1), 500 (50 * 10), 1400 (50 * 28), 2300 (50 * 46)
+ 4
+ """
+ i = 1
+ count = 0
+ while i <= n:
+ if sum_digits(n * i) == 5:
+ count += 1
+ i += 1
+ return count
+
+def count_primes(n):
+ """Return the number of prime numbers up to and including n.
+ >>> count_primes(6) # 2, 3, 5
+ 3
+ >>> count_primes(13) # 2, 3, 5, 7, 11, 13
+ 6
+ """
+ i = 1
+ count = 0
+ while i <= n:
+ if is_prime(i):
+ count += 1
+ i += 1
+ return count
+
+
+
+
The implementations look quite similar! Generalize this logic by writing a
+function count_cond, which takes in a two-argument predicate function
+condition(n, i). count_cond returns a one-argument function that takes
+in n, which counts all the numbers from 1 to n that satisfy condition
+when called.
+
+
Note:
+When we say condition is a predicate function, we mean that it is
+a function that will return True or False.
+
+
+
+
def sum_digits(y):
+ """Return the sum of the digits of non-negative integer y."""
+ total = 0
+ while y > 0:
+ total, y = total + y % 10, y // 10
+ return total
+
+def is_prime(n):
+ """Return whether positive integer n is prime."""
+ if n == 1:
+ return False
+ k = 2
+ while k < n:
+ if n % k == 0:
+ return False
+ k += 1
+ return True
+
+def count_cond(condition):
+ """Returns a function with one parameter N that counts all the numbers from
+ 1 to N that satisfy the two-argument predicate function Condition, where
+ the first argument for Condition is N and the second argument is the
+ number from 1 to N.
+
+ >>> count_fives = count_cond(lambda n, i: sum_digits(n * i) == 5)
+ >>> count_fives(10) # 50 (10 * 5)
+ 1
+ >>> count_fives(50) # 50 (50 * 1), 500 (50 * 10), 1400 (50 * 28), 2300 (50 * 46)
+ 4
+
+ >>> is_i_prime = lambda n, i: is_prime(i) # need to pass 2-argument function into count_cond
+ >>> count_primes = count_cond(is_i_prime)
+ >>> count_primes(2) # 2
+ 1
+ >>> count_primes(3) # 2, 3
+ 2
+ >>> count_primes(4) # 2, 3
+ 2
+ >>> count_primes(5) # 2, 3, 5
+ 3
+ >>> count_primes(20) # 2, 3, 5, 7, 11, 13, 17, 19
+ 8
+ """
+
def counter(n):
+ i = 1
+ count = 0
+ while i <= n:
+ if condition(n, i):
+ count += 1
+ i += 1
+ return count
+ return counter
+
+
+
+
+
+
One question that might be nice to ask is:
+in what ways is the logic for count_fives and count_primes similar,
+and in what ways are they different?
+
+
The answer to the first question can tell us the logic that we want to
+include in our count_cond function, while the answer to the second
+question can tell us where in count_cond we want to be able to have
+the difference in behavior observed between count_fives and
+count_primes.
+
+
It'll be helpful to also keep in mind that we want count_cond to return
+a function that, when an argument n is passed in, will behave similarly
+to count_fives or count_primes. In other words, count_cond is a
+higher order function that returns a function, that then contains the
+logic common to both count_fives and count_primes.
+
+
+
+
Use Ok to test your code:
python3 ok -q count_cond
+
+
+
+
+
Check Your Score Locally
+
+
You can locally check your score on each question of this assignment by running
+
+
python3 ok --score
+
+
This does NOT submit the assignment! When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it.
+
+
+
Submit Assignment
+
+
+
Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment.Lab 00 has detailed instructions.
+
+
+
Environment Diagram Practice
+
+
+
There is no Gradescope submission for this component.
+
+
However, we still encourage you to do this problem on paper to develop
+familiarity with Environment Diagrams, which might appear in an alternate
+form on the exam. To check your work, you can try putting the code into PythonTutor.
+
+
+
Optional Questions
+
+
+
These questions are optional. If you don't complete them, you will
+still receive credit for this assignment. They are great practice, so do them
+anyway!
+
+
+
Q4: Multiple
+
+
Write a function that takes in two numbers and returns the smallest number that
+is a multiple of both.
+
+
+
def multiple(a, b):
+ """Return the smallest number n that is a multiple of both a and b.
+
+ >>> multiple(3, 4)
+ 12
+ >>> multiple(14, 21)
+ 42
+ """
+
n = 1
+ while True:
+ if n % a == 0 and n % b == 0:
+ return n
+ n += 1