Tutorial A9¶
1 Write a set of functions that can be used to maintain a shopping-list saved to a file on disk. We want to represent the shopping list in memory as a dictionary with items to buy as keys and quantities as values. On disk we need a text file with two columns (items, quantity). In the first line, add a comment explaining the content (starting with a #
). We need the following functions (names are of course free to change):
read
: the function should read a file from disk in the expected format and return a shopping-list dictionary. The function needs to handle the situation in which no file is found to read from.
write
: the function should get a dictionary and write the current state of the shopping-list to disk.
add_item
: the function should get a new item we need to buy (string) and a quantity (integer; let’s neglect units here for the sake of simplicity). The item should be added to our dictionary and the file on disk should be updated automatically. The function needs to know the current state of the shopping-list (the location of the file on disk). Advanced If an item we want to add to the list is already in there, add the quantities.
Advanced
cross_off_item
: the function should get an item we have bought and a quantity. Subtract the quantity from the corresponding item in the list. Remove the item completely, if we have bought enough. Print a message, if the item was not in the list in the first place.
Advanced
pretty_print
: the function should display the content of the shopping-list dictionary in a nicer format. Print for each item the quantities after a newline and indented by four spaces.
Demonstrate your functions in action.