Lab 6: Dictionaries and Strings
- Due: Friday 10/09 @ 11:59pm
- Points: 1
- Download: lab06.zip
Attendance
You need to submit the lab problems in addition to attending to get credit for lab. Students in mega lab only need to submit the lab problems. Preceptor interviews are highly recommended but not required for lab submissions.
If you are in regular lab, your TA will come around during lab to check you in. If you didn't attend for a good reason (such as being sick), fill out this form (within 2 weeks of your lab): attendance form.
Required Questions
Review
Dictionaries
A dictionary contains key-value pairs and allows the values to be looked up by their key using square brackets. Each key must be unique.
>>> d = {2: 4, 'two': ['four'], (1, 1): 4}
>>> d[2]
4
>>> d['two']
['four']
>>> d[(1, 1)]
4
The sequence of keys or values or key-value pairs can be accessed using
.keys() or .values() or .items().
>>> for k in d.keys():
... print(k)
...
2
two
(1, 1)
>>> for v in d.values():
... print(v)
...
4
['four']
4
>>> for k, v in d.items():
... print(k, v)
...
2 4
two ['four']
(1, 1) 4
By default, iterating through a dictionary iterates through its keys.
>>> for x in d:
... print(x)
...
2
two
(1, 1)
You can check whether a dictionary contains a key using in:
>>> 'two' in d
True
>>> 4 in d
False
Attempting to access a key that does not exist in a dictionary will cause an
error. You can use .get(<key>, <default>), which returns the value
corresponding to <key> in a dictionary or, if it doesn't exist, returns
<default>.
>>> d[3]
KeyError: 3
>>> d.get(3, "fun")
'fun'
>>> d.get(2, "fun")
4
The contents of a dictionary can be modified using =:
>>> d
{2: 4, 'two': ['four'], (1, 1): 4}
>>> d[(1, 1)] = "61a"
>>> d[(1, 1)]
'61a'
A dictionary comprehension is an expression that evaluates to a new dictionary.
>>> {3*x: 3*x + 1 for x in range(2, 5)}
{6: 7, 9: 10, 12: 13}
Type Hints
Type hints can appear def statements (and a few other
places) to indicate the types of value that a variable should have or that
functions should return.
An example without type hints:
def pair(y, z):
return [y, z]
The same example with type hints that y, and z are integers and the
pair function returns a list of integers:
def pair(y: int, z: int) -> list[int]:
return [y, z]
Code behaves identically with or without type hints.
(Optional) Automatic Type Checking: VS Code can be configured to annotate
locations where a variable has been assigned a value that does not have the
expected type. To enable type checking, open the VS Code settings, which you can
do by pressing the Command and , keys on a Mac, or the Control and , keys
simultaneously on a Windows machine. Type type checking in the search bar,
which should pull up the Type Checking options. Use the dropdown menu to change
type checking from the default of off to basic.
If these type checking options did not appear, you may need to install the
Pylance extension. Open the Extensions view by holding Shift, Command, and X
on a Mac or Shift, Control, and X on Windows. Type Pylance in the search
bar, and press the install button.
To check to ensure that type checking has been enabled, type the following into a Python file:
def f(x: int):
return x
f('not an int')
You should see a red underline under 'not an int'. If you hover over
'not an int', VS Code displays an error message, explaining that
'not an int' does not match the expected type int. Keep an eye out for
these errors while you're writing code! They're often a hint about where
your code has a bug.
What Would Python Display? (WWPD)
Q1: WWPD: Dictionaries
Predict what Python will display when the following lines are entered into an interactive session, then unlock the test to check your answers:
python3 -m pytest -k dictionaries_wwpd --unlockUnlocking Examples
>>> pokemon = {'pikachu': 25, 'dragonair': 148, 'mew': 151}
>>> pokemon['pikachu']
______
>>> len(pokemon)
______
>>> 'mewtwo' in pokemon
______
>>> 'pikachu' in pokemon
______
>>> 25 in pokemon
______
>>> 148 in pokemon.values()
______
>>> pokemon.get('mew', 100000)
______
>>> pokemon.get('mewtwo', 10)
______
>>> {pokemon[k]: k for k in pokemon if len(k) < 5}
______
>>> min(pokemon, key=len)
______
>>> pokemon[min(pokemon, key=len)]
______
Write Code
Q2: Displaying Fruit
Implement display, which takes a string fruit naming a fruit in plural form
(such as 'apples') and a positive integer count. It returns a string that
shows the count and the fruit inside angle brackets, such as '<3 apples>'.
When count is 1, the fruit name should be singular: drop the final s, so
that display('apples', 1) returns '<1 apple>'. Assume that every plural
fruit name can be made singular by removing the last letter.
Hint:
str(n)converts an integernto a string, and+joins strings together. A string can be sliced.
def display(fruit: str, count: int) -> str:
"""Display a count of a fruit in angle brackets.
>>> display('apples', 3)
'<3 apples>'
>>> display('apples', 1)
'<1 apple>'
>>> display('kiwis', 12)
'<12 kiwis>'
>>> print(display('apples', 3) + display('kiwis', 3))
<3 apples><3 kiwis>
"""
assert count >= 1 and fruit[-1] == 's'
"*** YOUR CODE HERE ***"
python3 -m pytest -k displayQ3: Buying Fruit
Implement the buy function that takes three parameters:
fruits_to_buy: A list of strings representing the fruits you need to buy. At least one of each fruit must be bought.prices: A dictionary where the keys are fruit names (strings) and the values are positive integers representing the cost of each fruit.total_amount: An integer representing the total money available for purchasing the fruits.
Take a look at the docstring for more details on the input structure.
The function should print all possible ways to buy the required fruits so
that the combined cost equals total_amount. You can only select fruits
mentioned in the fruits_to_buy list.
Note: Use the
displayfunction from the previous question to format the output. Calldisplay(fruit, count)for each fruit and its corresponding quantity to generate a string showing the type and amount of fruit bought.
def buy(fruits_to_buy: list[str], prices: dict[str, int], total_amount: int) -> None:
"""Print ways to buy some of each fruit so that the sum of prices is amount.
>>> prices = {'oranges': 4, 'apples': 3, 'bananas': 2, 'kiwis': 9}
>>> buy(['apples', 'oranges', 'bananas'], prices, 12) # We can only buy apple, orange, and banana, but not kiwi
<2 apples><1 orange><1 banana>
>>> buy(['apples', 'oranges', 'bananas'], prices, 16)
<2 apples><1 orange><3 bananas>
<2 apples><2 oranges><1 banana>
>>> buy(['apples', 'kiwis'], prices, 36)
<3 apples><3 kiwis>
<6 apples><2 kiwis>
<9 apples><1 kiwi>
"""
def add(fruits: list[str], amount: int, cart: str) -> None:
if fruits == [] and amount == 0:
print(cart)
elif fruits and amount > 0:
fruit = fruits[0]
price = ____
for k in ____:
# Hint: The display function will help you add fruit to the cart.
add(____, ____, ____)
add(fruits_to_buy, total_amount, '')
python3 -m pytest -k buySubmit Assignment
Submit this assignment by running Provenance: Prepare Submission Bundle from the VS Code command palette and uploading the resulting zip to Gradescope. The zip already contains the files you've edited. Lab 00 has detailed instructions.
Your responses to WWPD questions are not submitted, and they do not need to be. Lab credit is based on the code writing questions.