Welcome to Discussion 3! Today we will examine the topics of mental health and social media (in preparation of the final SRC!). Our focus is primarily on brainstorming solutions to problems arising from tech.
Here are the SRC Discussion slides.
–
Let's get some more practice with our new favorite programming language, Python!
Our goal for lab this week is to get you comfortable with Python syntax, for loops, debugging, and Python's built-in function for sorting lists.
If you don't feel confident about any of these topics after your lab session, definitely come to TA Hours! We'd love to help you.
If you haven't yet installed VSCode, the editor we'll be using to write our Python programs, let's get set up with that now!
Follow the VSCode Installation and Project Setup guide! If you get stuck or run into problems at any step, call over a TA!
Consider the following function, add_underscores(word: str) -> str
, which takes in a word and returns that same word, but with underscores added before and after each letter in the word (i.e. "hello"
-> "_h_e_l_l_o_"
):
Copy and paste this snippet of code into a Python file, and run the program. You should see this output:
Uh oh! We were expecting to get _h_e_l_l_o_
, so this means our program has a bug! Let's use the VSCode Debugger to find it. Click on the arrow next to the play button on the top right of your window and click "Debug Python File":
After that, the debugger should open at the bottom of your screen.
The area where our bug must be occurring is at the line that says new_word = word[i] + "_"
, since that's where we're supposed to be adding underscores but are currently failing to do so properly.
To investigate this line of code in particular, we're going to use a breakpoint, which will stop our code at a certain line so we can see values of variables and how they change at a given moment in time.
To add a breakpoint, click on the line number to the left of your code.
Now, click "Debug Python File" again. At your screen, you should see something like this:
Now we can see the values of i
, new_word
, and word
at the moment in time when our program reaches that line where we set the breakpoint!
There are a few important buttons here:
Play around with the blue play button and the "Step Into" button. Can you find the bug? Once you find the it, fix the bug in the code!
print
While VSCode's debugger can be useful, sometimes we want a quicker, less rigorous option for debugging. Let's look at another program:
Copy and paste this piece of code into VSCode and run the program. What does it print?
The body of our function is a bit confusing – let's try to figure out what it's doing. While the VSCode debugger could be used here, it might not immediately be instructive as to what the function is actually doing.
To see what our function is actually doing, let's see how we can place print
statements within our function to help us decipher what is changing and when.
Add this print
statement within your for loop, above the if-statements:
Now run your program – before it prints out the result of calling mystery_fun(input)
, it should print a bunch of numbers that correspond to num_list[num]
at each iteration of the loop.
Can you see more clearly how return_value
changes throughout this function? Describe how return_value
is modified as it progresses through each number in input
.
HINT: If you're not sure yet, try adding other print
statements to make it more clear what's going on.
Call over a TA once you reach this point.
Compare and contrast debugging with print vs. with the debugger. Note that the TA can ask either partner to answer, so please make sure both partners understand what's going on.
Katie has grown tired of Disney's antics and decides to take matters into her own hands to find out Hannah Montana's true identity. She recalls that Hannah is a student at the nearby Massachussetts Institute of Technology, or MassTech. She decideds to infiltrate MassTech and get to know Hannah so she can find her real identity. For Katie to believably pass as a MassTech student, she must first take some classes on the renowned MassTech platform, OpenCourseWare. Here is a list of the courses that she can enroll in right now:
NOTE: To do many of the following problems, you will need to do something called string slicing. String slicing is the Python equivalent of Pyret's string-substring
, but winds up being a lot more powerful.
Let's say you have the string str = "Beep!"
. Just like in Pyret, strings in Python are 0-indexed:
To access the characters at those indices, use the notation: str[index]
. For example,
If you want to slice a string into a substring of more than one character, use the notation: str[start:end]
where start
represents the first index of the substring (inclusive) and end
represents the last index of the substring (exclusive). For example,
That's all you need to know for the lab, but Python has a few additional shortcuts for string slicing that might be useful in the long run:
If you leave off the start or end index, Python assumes you want to start at 0 and end at the end of the string:
Negative numbers let you index from the end of a string
Katie got over-excited and registered for so many courses that she can't keep track of them anymore! Help her sort through and organize her courses using Python:
Write a function dept_courses(dept: str)
that takes in a 4-letter department code and produces a list of all courses in department dept
. Then, write a function course_num(num: str)
that takes in a 4-digit course number (as a string) and produces a list of all courses with that number (regardless of department).
Write a function course_search(dept: str, min: int, max: int)
that takes in a 4-letter department code, a minimum course code, and a maximum course code, and produces a list of all courses in department dept
with numbers between min
and max
, inclusive.
Write a function pretty_print(dept: str)
that takes in a 4-letter department code and prints out the full name of a department followed by all of its courses. Each course should be on a separate line with "-" before the course name.
For example:
Write a function compare_depts(dept1: str, dept2: str)
that takes in the 4-letter department codes of two departments and returns the 4-letter department code of the department that is offering more courses. If both departments are offering the same number of courses, the function should return "equal" (str
). If a department isn't offering any courses, raise an exception.
Katie has a couple of other tasks she needs to write some Python code for:
Write a function obscure
that takes a string and replaces certain letters with numbers (a common, but ineffective, password protection technique). Specifically, convert every e (or E) to 3, every i (or I) to 1, and every o (or O) to zero. Write a helper function that takes in a single character and converts it if necessary (and keeps it the same if not).
NOTE: You can use == to compare strings, or check whether a character is in a list (such as ["a", "A"]) of characters to be treated similarly. To check whether an item is in a list, use an in
expression of the form item in list
.
Write a function sorted_increasing
that determines whether a list of numbers is sorted into increasing order.
NOTE: The Boolean type is written as bool
in Python; True
and False
(with first letter capital) are the two boolean values.
HINT: The challenge here is to figure out how to track the previous number in the list. Think about how a variable could help you do that.
Write a function first_five_pos
that takes a list and returns a list of the first five positive numbers from the input list.
Python has a useful and customizable sorting function that operates on lists. In this section, we will explore how to use it.
The simplest version of the function is sorted(lst: list)
, which takes in a list and sorts it in ascending order.
False
s before all True
sFor example:
To sort a list in descending order, add the input reverse=True
to the function call. Here are the examples from above but sorted in reverse:
NOTE: Notation like reverse=True
is used for optional inputs to a function, a concept we did not see in Pyret. Since an optional input might not be provided, we need the <name>=
part to indicate which optional parameter is being used.
In most cases, default sorting is enough. However, what if you want to sort a list in a specific, custom way? To do so, add the input key=my_fun
where my_fun
represents a function that takes in a single list element. my_fun
is called on each element in the list, and its output determines the sort order.
Let's take a look at a concrete example. The following function takes in a string and returns its length:
With key_fun
defined, we can do the following to sort the list by string length:
(Note that since string length is an integer, sorted
defaults to sorting the elements in increasing order)
Let's apply the ideas of sorting discussed above to the course list examples from earlier:
Sort course_list
in alphabetical order by department code.
Sort course_list
by course number, regardless of department code.
After gaining Hannah Montana's trust, Katie has signed up to compete in a Mystery Scrabble competition with her. Unfortunately, Katie happens to be very bad at this game and needs your help to win so she can maintain her guise of being a MassTech student. She wants to use custom sorting to efficiently find the best word. In this version of Scrabble, point values for words are based solely on the length of a word, rather than the letters themselves. Given a list of possible words, she wants to know which ones will secure them the most points – so instead of sorting the list alphabetically, she sorts the list based on the length of each word in it.
Another way to think about what's happening is to imagine mapping the key
function on the list, sorting, and then undoing the mapping. In other words:
Step 1 (the original list): ["BuzzAldrin", "really", "loves", "sorting"]
Step 2 (the mapped list): [10, 6, 5, 7]
Step 3 (the sorted order): [5, 6, 7, 10]
Step 4 (the "un-mapped" list): ["loves", "really", "sorting", "BuzzAldrin"]
NOTE: Note that if multiple elements mapped to the same thing – in this case, multiple words had the same number of letters – they would stay in their original order (this is called stable sorting).
Katie has decided to up the ante by adding some new, more complex, rules to the game. Awarding a point value for a word has been adjusted to the following:
Write a function sort_by_score(lst : list)
that takes in a list of strings and sorts them by their score (in descending order, i.e. highest to lowest) using the updated scoring system. Assume all strings in the list are only made up of alphabetical characters (no numerical, punctuation, spaces, etc.).
For example, "beep" has a score of 2+1+1+2=6 and sort_by_score(["aaa", "aba", "z", "beep", "BOOP"])
should return ["beep", "BOOP", "z", "aba", "aaa"]
.
Katie and Hannah had a blast at Board Game Night together. Needless to say, Mystery Scrabble was a hit, and Katie was able to avoid having her cover blown. She used the custom-sorting functions to win the game and figure out her courseload, and now she's ready to learn Hannah Montana's true identity!