.py
files containing your work. (If you upload a screenshot or other file format, you won't get credit.)This homework assignment must be submitted in Gradescope by Noon central time on Tuesday 25 January 2022.
Collaboration is prohibited, and you may only access resources (books, online, etc.) listed below.
The course materials you may refer to for this homework are:
This homework assignment has 2 problems, numbered 2 and 3. The grading breakdown is:
Points | Item |
---|---|
2 | Autograder |
4 | Problem 2 |
4 | Problem 3 |
10 | Total |
The part marked "autograder" reflects points assigned to your submission based on some simple automated checks for Python syntax, etc. The result of these checks is shown immediately after you submit.
Ask your instructor or TA a question by email, in office hours, or on discord.
In Gradescope, the score assigned to your homework submission by the autograder (checking for syntax and docstrings) will be recorded as "Problem 1". Therefore, the numbering of the actual problems begins with 2.
An element of a list is a local extremum if one of these conditions holds:
Note an element can be both a local maximum and local minimum!
In a file hwk2prob2.py
, write a function LEC(L)
that takes a list L
whose elements are floats or integers and returns the number of local extrema in the list.
Suggested strategy: Test each element of the list to see whether it satisfies one of the conditions above, keeping a running count to return at the end.
Some cases to think about / test:
L = [275,275,275,275,275]
), then every element of the list is both a local maximum and a local minimum, and so the return value of LEC
would be the length of the list. (Don't check for this separately; it should be a consequence L
has 0 or 1 elements, then there are no neighbors so the definition breaks down. In these cases, just return len(L)
.Sample return values for certain inputs are shown below.
LEC([])
LEC([275])
LEC([1,2,3,4])
LEC([1,2,3,4,5,6,7,8,9,10])
LEC([3,1,4,1,5,9,2,6,5,3,5,8]) # length is 12, but indices 4, 8, and 10 are not local extrema
LEC([5,5,5,5,5,5,5]) # length 7, all equal, hence all extrema
LEC([1,1,2,2]) # all are extrema: [local max and min, local min, local max, local max and min]
Imagine you have a standard cubical die whose six sides are labeled with these numbers:
-3, -2, -1, 1, 2,3
Using such a die you can play the following game: You start with a score of 0 points. Each time you roll the die, you add the number that shows up to your score. If your score ever returns to 0 points again, you win.
In a file hwk2prob3.py
, write a program that plays this game 10 times, each time printing how many rolls it took to win. The output should look like this:
Game ended after 219 rolls
Game ended after 2 rolls
Game ended after 2 rolls
Game ended after 6 rolls
Game ended after 4 rolls
Game ended after 4 rolls
Game ended after 1202 rolls
Game ended after 2 rolls
Game ended after 37 rolls
Game ended after 4 rolls