Skip to document
This is a Premium Document. Some documents on Studocu are Premium. Upgrade to Premium to unlock it.

Grok worksheet 11

Grok worksheet 11 with summary and sample solutions
Course

Foundations Of Computing (COMP10001)

375 Documents
Students shared 375 documents in this course
Academic year: 2021/2022
Uploaded by:
Anonymous Student
This document has been uploaded by a student, just like you, who decided to remain anonymous.
University of Melbourne

Comments

Please sign in or register to post comments.

Related Studylists

FOC

Preview text

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

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.

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.

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. 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.

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:

Was this document helpful?
This is a Premium Document. Some documents on Studocu are Premium. Upgrade to Premium to unlock it.

Grok worksheet 11

Course: Foundations Of Computing (COMP10001)

375 Documents
Students shared 375 documents in this course
Was this document helpful?

This is a preview

Do you want full access? Go Premium and unlock all 13 pages
  • Access to all documents

  • Get Unlimited Downloads

  • Improve your grades

Upload

Share your documents to unlock

Already Premium?
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

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.