
Lab 6: Mutability, Iterators lab06.zip
CS61A学习记录,可参考https://cs61a.org/
Q1: WWPD: List-Mutation
Use Ok to test your knowledge with the following “What Would Python Display?” questions:
1 python3 ok -q list-mutation -u✂️Important: For all WWPD questions, type
Function
if you believe the answer is<function...>
,Error
if it errors, andNothing
if nothing is displayed.
1 | >>> lst = [5, 6, 7, 8] |
Q2: Insert Items
Write a function which takes in a list lst
, an argument entry
, and another argument elem
. This function will check through each item in lst
to see if it is equal to entry
. Upon finding an item equal to entry
, the function should modify the list by placing elem
into lst
right after the item. At the end of the function, the modified list should be returned.
See the doctests for examples on how this function is utilized.
Important: Use list mutation to modify the original list. No new lists should be created or returned.
Note: If the values passed into
entry
andelem
are equivalent, make sure you’re not creating an infinitely long list while iterating through it. If you find that your code is taking more than a few seconds to run, the function may be in an infinite loop of inserting new values.
1 | def insert_items(lst, entry, elem): |
Iterators
Q3: WWPD: Iterators
Use Ok to test your knowledge with the following “What Would Python Display?” questions:
1 python3 ok -q iterators-wwpd -u✂️Python’s built-in
map
,filter
, andzip
functions return iterators, not lists. These built-in functions are different from themy_map
andmy_filter
functions we implemented in Discussion 05.Important: Enter
StopIteration
if aStopIteration
exception occurs,Error
if you believe a different error occurs, andIterator
if the output is an iterator object.
1 | >>> s = [1, 2, 3, 4] |
Q4: Count Occurrences
Implement count_occurrences
, which takes in an iterator t
and returns the number of times the value x
appears in the first n
elements of t
. A value appears in a sequence of elements if it is equal to an entry in the sequence.
Note: You can assume that
t
will have at leastn
elements.
1 | def count_occurrences(t, n, x): |
Q5: Repeated
Implement repeated
, which takes in an iterator t
and returns the first value in t
that appears k
times in a row.
Note: You can assume that the iterator
t
will have a value that appears at leastk
times in a row. If you are receiving aStopIteration
, yourrepeated
function is likely not identifying the correct value.
Your implementation should iterate through the items in a way such that if the same iterator is passed into repeated
twice, it should continue in the second call at the point it left off in the first. An example of this behavior is in the doctests.
1 | def repeated(t, k): |