Grok worksheet 11 PDF

Title Grok worksheet 11
Course Foundations Of Computing
Institution University of Melbourne
Pages 13
File Size 977.4 KB
File Type PDF
Total Downloads 80
Total Views 138

Summary

Grok worksheet 11 with summary and sample solutions...


Description

Grok 11 Dictionaries Dictionaries allow you to create mappings from keys to values. For example, you might use a dictionary to map Australian state names to the names of their corresponding capital cities:

(Yes, there is an intentional mistake in there — Melbie. We'll fix it shortly.) The keys in the above dictionary are strings which represent the names of the Australian states. Each key maps to a value, which also happens to be a string in this case. In the general case, the keys and values can be of different types. Dictionary values are constructed using the curly brace characters { and }. As a special case, you can construct an empty dictionary using an opening and closing brace with nothing in between:

In the above code, an empty dictionary is created and assigned to the variable example_empty_dict. Currently this dictionary contains no mappings, so it is fairly uninteresting. As you shall soon see, it is possible to add new mappings to an existing dictionary, so it can be useful to construct empty dictionaries and later add values as necessary.

Indexing Dictionaries Like lists and strings, dictionaries are indexable. However, the indices of dictionaries are keys of arbitrary value, whereas the indices of lists and strings are always integers. A given key can only occur once in the dictionary, and is associated with a unique value (but you can, of course, make the value a list containing multiple objects). You can look up values in

a dictionary using the normal indexing notation:

Dictionary Methods Some other ways of indexing dictionaries are the pop and get methods. These return a value given a key. As you might expect, pop deletes the (key, value) pair after returning the value, just like with lists.

The clear method deletes the entire contents of the dictionary, and del removes a key:value pair without returning anything:

Updating Dictionaries

You can change the value which is associated with a key or add a new key and value pair to the dictionary using the assignment (=) operator:

Victoria' now maps to the value 'Melbourne' instead of 'Melbie', thus fixing the previous mistake. The key 'ACT' was not present in the dictionary before the assignment statement, so the above code extends the dictionary with a new mapping.

Testing Dictionary Membership You can test if a key is present in a dictionary using the in operator. Try running the following code a few times, entering both valid and invalid state names:

Accessing all Keys You can get the keys in a dictionary using the keys method. keys returns a special iterable collection called a dict_keys view object that supports iteration and the in operator like a list, but does not support indexing:

Accessing all Values You can get the values in a dictionary (separate from the keys) using the values method. values returns a special iterable collection called a dict_values object that acts much like the dict_keys object:

Accessing All Keys and Values

Another useful method for dictionaries is the items method. Like keys and values, items returns a view object called dict_items containing tuples of the (key, value) pairs. You can also convert these view objects into lists using list.

Further Notes Keys for dictionaries can only be immutable objects. That means you can use: int, float, str, tuple, bool as keys, but you cannot use: list, set. Could you use dictionaries? Are they mutable or immutable? Another important characteristic of dictionaries is that they are not ordered. This can be seen by observing the order of the (key, value) pairs when the items method is called is different to the order of insertion of the pairs. This also means that when you iterate over a dictionary, you have to keep this in mind: the order may change!

Finally, what happens when we put the same key in with a different value? Have a look at the last example. The final value is kept.

Capital City Testing Write a function is_capital(state, city) that returns True if the named city is the capital of the named state and False otherwise. Every city and state in the following table should be recognised.

State

Capital city

New South Wales

Sydney

Queensland

Brisbane

South Australia

Adelaide

Tasmania

Hobart

Victoria

Melbourne

Western Australia

Perth

If a city or state is not in the table the function must return False. Here are some examples of how your function should work:

Counting Things with Dictionaries A common programming task is to keep a tally of how many times various items appear in a piece of data. Below is an example program which counts the number of occurrences of each letter in the first paragraph of Moby Dick:

The above code assigns the text of the first paragraph of Moby Dick to the variable MOBY. A new empty dictionary is created and assigned to tally. The for loop counts the number of times each character appears in the string assigned to MOBY. Each iteration, the code checks if the current letter char is already in the tally dictionary. If yes, its corresponding count is incremented. If not, it is added to the dictionary and its count is set to 1. The reason we need to do this is that if we attempt to increment a value associated with a non-existent key, we will get a KeyError (because there is no pre-existing value to increment):

When the program completes, it prints out the number of instances of the letters C and I in the text.

Character Histogram After counting all the characters in Moby Dick's first paragraph, you can do interesting things with the information. For instance, you can print out a simple bar chart of the frequencies for

all the upper case characters which appear in the text:

For each of the keys in tally, the code checks if it is an upper case character using isupper. If it is upper case, it prints a bar with the number of occurrences of = equal to the count of that character in tally. From the output of the code you can see that, for instance, there are two occurrences of C in the text, and 12 occurrences of I.

Number of Frequent Characters Create a function freq_threshold(text, n) which returns the number of characters whose frequency in a given piece of text is strictly greater than a threshold value n (a nonnegative integer). The examples below assume that the first paragraph from Moby Dick has been read into the variable MOBY, which we achieve by importing variables from the file constants.py. Note that you are welcome to re-use code from earlier problems relating to this text. Here are some examples of how your function should behave:

Duplicate Word Write a function repeat_word_count(text, n) that takes a string text and a positive integer n, converts text into a list of words based on simple whitespace separation (with no removal of punctuation or changing of case), and returns a sorted list of words that occur nor more times in text. For example:

Mode List Write a function mode(numlist) that takes a single argument numlist (a non-empty list of numbers), and returns the sorted list of numbers which appear with the highest frequency in numlist (i.e. the mode). For example:

Top-5 Frequent Words Write a function top5_words(text) that takes a single argument text (a non-empty string), tokenises text into words based on whitespace (once again, without any stripping of punctuation or case normalisation), and returns the top-5 words as a list of strings, in descending order of frequency. If there is a tie in frequency at any point, the words with the same frequency should be sub-sorted alphabetically. If there are less than five distinct words in text, the function should return the words in descending order of frequency (with the same tie-breaking mechanism). For example:

Sets Finally, we introduce a useful but somewhat obscure data structure called a set. If you are familiar with sets in mathematics, it is exactly the same concept. For the rest of us, a set is like a list, but with unique elements, and no order. Below we define an empty set and a set with some elements. Note: 

Although a set with elements uses curly braces, you cannot use empty curly braces to define an empty set as that would be an empty dictionary.



Try running the code below more than once. Does the order of my_set2 change? Why?

Because sets contain unique elements, they automatically remove duplicate elements.

Useful Set Operators

You can make sets from sequences. This is a good hack for removing duplicate elements:

You can take the difference between sets, join them together (find their union = |), and find their intersection (the elements that are in both = &).

Useful Set Methods Finally, as with lists, sets are mutable, so you can add and remove elements:

Because sets have no order, it does not make sense to index or slice them. You cannot do this. You can also find the length of a set.

Mutual Friends Write a function mutual_friends(list1,list2) that takes two lists of friends and returns the number of friends in common. Use sets. Your problem should behave as follows:...


Similar Free PDFs