In this exercise you will get some practice with some dictionary functions.
Assignment Outline
invert
– 20 Points Autograded- Unit Tests – 5 Points Autograded
count
– 30 Points Autograded- Unit Tests – 5 Points Autograded
favorite_colors
– 30 Points Autograded- Unit Tests – 5 Points Autograded
Style, Linting, Typing – 20 Points Autograded
Note: Even if your functions are not 100% correct or finished, you can get full credit for the unit tests if you set up a function skeleton and write your tests assuming correct functionality.
0. Setup
Create a new directory in exercises
named ex07
.
Inside the exercises/ex07
directory, create a file named dictionary.py
. Add a docstring and establish an __author__
variable to be assigned a string with the digits of your PID. This is where you will implement your function skeletons and implementations below.
Unit Tests
Also inside the exercises/ex07
directory, create a file named dictionary_test.py
. Add a docstring and establish an __author__
in this file as well.
For each function from below (invert
, favorite_color
, count
), you are to define at least 3x unit test functions. Remember that a unit test function starts with test_
.
The 3 unit tests should consist of:
- One edge case
- Two use cases
Include descriptive function names and docstrings, so that it captures what is being tested.
The command to run your tests is python -m pytest exercises/ex07
or you can run them using the beaker tab in VSCode if it is working (do note the VSCode testing feature tends to be a bit flaky).
Just like in ex06
, you will need to import your functions in your tests file.
If your screen is large enough, you are encouraged to open these files side-by-side in VSCode by dragging the tab of one to the right side of VSCode so that it changes to a split pane view. Closing your file explorer can help give you additional horizontal space.
1. invert
This is the first function you will write in dictionary.py
. The other two functions will also be defined in this file.
Given a dictionary
of [str, str]
, invert
should return a dict[str, str]
that inverts the keys and the values. The keys of the input list becomes the values of the output list and vice versa.
Remember that keys in a dictionary are unique. If you encounter more than one of the same key when trying to invert your dictionary, i.e., raise a KeyError. Example usage:
>>> invert({'a': 'z', 'b' : 'y', 'c': 'x'})
{'z': 'a', 'y': 'b', 'x': 'c'}
>>> invert({'apple': 'cat'})
{'cat': 'apple'}
>>> invert({'kris': 'jordan', 'michael': 'jordan'})
KeyError
Similar to how you raised a ValueError
in the max
function for list
utils, the syntax for raising a KeyError
is: `raise KeyError(“error message of your choice here!”)
Testing for KeyError:
You may optionally add a test for the invert function to check if the KeyError is being raised. Testing errors requires different syntax than testing normal outputs. If an error is raised then the function never actually returned anything, so we are unable to assert
a return value. Instead try the following:
- Make sure to
import pytest
- Use the following code as an example:
with pytest.raises(KeyError):
= {'kris': 'jordan', 'michael': 'jordan'}
my_dictionary invert(my_dictionary)
2. favorite colors
Create a function in your dictionary.py
file called favorite_color
. It has the following specifications:
- It has one parameter, of type
dict[str, str]
of names and favorite colors. - It returns a
str
which is the color that appears most frequently.- If there is a tie for most popular color, return the color that appeared in the dictionary first.
You can also check the correctness of your favorite_color
function by calling it in main
, printing the result, then running the program with the same command from above.
An example:
print(favorite_color({"Marc": "yellow", "Ezri": "blue", "Kris": "blue"}))
The results of which would look like:
$ python -m exercises.ex07.favorite_color
blue
3. count
Given a list[str]
, this function will produce a dict[str, int]
where each key is a unique value in the given list and each value associated is the count of the number of times that value appeared in the input list.
- Function name:
count
- Parameter:
list[str]
- list of values to count the frequencies of - Return Type:
dict[str, int]
- a dictionary of the counts of each of the items in the input list
Implementation strategy:
- Establish an empty dictionary to store your built-up result in
- Loop through each item in the input list
- Check to see if that item has already been established as a key in your dictionary. Try the following boolean conditional:
if <item> in <dict>:
– replacing<item>
with the variable name of the current value and<dict>
with the name of your result dictionary. - If the item is found in the dict, that means there is already a key/value pair where the item is a key. Increase the value associated with that key by 1 (counting it!)
- If the item is not found in the dict, that means this is the first time you are encountering the value and should assign an initial count of
1
to that key in the result dictionary.
- Check to see if that item has already been established as a key in your dictionary. Try the following boolean conditional:
- Return the resulting dictionary.
4. Make a Backup Checkpoint “Commit”
As you make progress on this exercise, making backups is encouraged.
- Open the Source Control panel (Command Palette: “Show SCM” or click the icon with three circles and lines on the activity panel).
- Notice the files listed under Changes. These are files you’ve made modifications to since your last backup.
- Move your mouse’s cursor over the word Changes and notice the + symbol that appears. Click that plus symbol to add all changes to the next backup. You will now see the files listed under “Staged Changes”.
- If you do not want to backup all changed files, you can select them individually. For this course you’re encouraged to back everything up.
- In the Message box, give a brief description of what you’ve changed and are backing up. This will help you find a specific backup (called a “commit”) if needed. In this case a message such as, “Progress on Exercise 3” will suffice.
- Press the Check icon to make a Commit (a version) of your work.
- Finally, press the Ellipses icon (…), look for “Pull/Push” submenu, and select “Push to…”, and in the dropdown select your backup repository.
5. Submit to Gradescope for Grading
Login to Gradescope and select the assignment named “EX07 - Dictionaries.”. You’ll see an area to upload a zip file. To produce a zip file for autograding, return back to Visual Studio Code.
If you do not see a Terminal at the bottom of your screen, open the Command Palette and search for “View: Toggle Integrated Terminal”.
Type the following command (all on a single line):
python -m tools.submission exercises/ex07
In the file explorer pane, look to find the zip file named “yy.mm.dd-hh.mm-exercises-ex07.zip”. The “yy”, “mm”, “dd”, and so on, are timestamps with the current month, day, hour, minute. If you right click on this file and select “Reveal in File Explorer” on Windows or “Reveal in Finder” on Mac, the zip file’s location on your computer will open. Upload this file to Gradescope to submit your work for this exercise.
Autograding will take a few moments to complete. If there are issues reported, you are encouraged to try and resolve them and resubmit. If for any reason you aren’t receiving full credit and aren’t sure what to try next, come give us a visit in office hours!