3.5. Python types assignment

[Note: this section is part of the online notes but it is really an document file created automatically from an ipython notebook session, to help you integrate it with your reading. To do the assignment, you really want to download [github_repo]/intro/python_types_assignment_2023.ipynb.]

3.5.1. Tuple and List Questions

The cell below contains an error. To see what the error is, position your cursor in the cell and type [Shift]-[Enter]. Explain what the error is in the cell 2 cells down (labeled Enter your answer here). (It is not a NameError; if you get a NameError, that’s because you haven’t executed the cell that defines the variable T first.) Explain how you could define T differently so that the expression in the cell below would not be an error.

T[1] = '1'
[Enter your answer here]

In the cell below, write an expression that computes the length of T.

[Enter your answer here]

Consider the following list:

Higgledypiggledy = [1, ['a','b','c'], (1.4, 'Sam')]

In the next cell, write an expression that retrieves the value ['a','b','c'] from Higgledypiggledy. For example, the expression Higgledypiggledy[0] retrieves the value 1. Test your answer by typing [Shift]-[Enter] to see what you get. If you get NameError, it’s because you didn’t first execute the expression in the cell above to define the variable Higgledypiggledy.

[Enter your answer here]

In the next cell, type a single expression that retrieves the value (1.4, 'Sam') from Higgledypiggledy and sets avariable to that value. This answer will be of the form Something = Something. The first something will be a variable name. You can choose any name you want as a variable name, as long as it is all letters (avoid numbers and special characters for now) and isn’t already reserved as the name of a builtin Python operator or function. Python will raise a SyntaxError if you use a reserved name.

[answer here]

In the next cell, type a single expression that retrieves the value "Sam" from Higgledypiggledy. If you can’t think of one expression that does this, you can use the variable you defined in cell [5] and retrieve "Sam" from that. But that won’t be as good because it takes two steps to retrieve value that could be retrieved in one step.

3.5.2. Strings

The cell below defines a string. Execute that definition. (This is another way of saying, “Place your cursor in the cell and type [Shift]-[Enter])”. Notice that when you evaluate this cell, Python doesn’t seem to do anything. Nevertheless it has changed its state to reflect the fact that the variable Example_str has been defined to denote a particular string.

Example_str = "rather"

In the next cell, write and execute an expression that retrieves the value "r" from Example_str. There are two r’s in the string, so there are two possible answers:

[answer here]

The string rather has the nice property that some of its substrings are English words. In the cell below write a single Python expression that retrieves the word rat from Example_str. You might need to review the lecture material on string slices :python_for_ss:book_draft/Python_introduction/strings.html. Evaluate it with [Shift]-[Enter] to check your answer.

[answer here]

In the same cell (the cell above), on new lines, write two more expressions that retrieve two other English words. Each time you add a line to the cell, type [Shift]-[Enter]. Notice that when there’s more than one line in the cell, Python only seems to be responding to the last line. This is how the Python Interpreter (the program you are interacting with when you type commands to Python) works. Despite the fact that Python only responds to the last line, all the lines are being executed.

3.5.3. Dictionaries

There are two ways to define dictionaries which are both worth knowing. We start with the easiest to type.

dd = dict(name = 'Mark Gawron',
          language = 'Python',
          favorite_tv_show = 'Monty Python',
          favorite_desert = 'Apple pie')

In the next cell down, write a single expression to retrieve the value "Python" from dd.

[answer here]

In the next cell down write an expression that adds information to dd. Specifically add the key favorite_baseball_team and set its value to be "Chicago Cubs". Note that strings can have spaces in them and still be valid strings.

[answer here]

In the next cell we use a different syntax for defining a dictionary.

letter_counts = {' ': 9, 'e': 5, 'o': 5, 'l': 3, 'd': 2,
                 'h': 2, 'r': 2, 'u': 2, 'w': 2, 'y': 2, '.': 1,
                 'a': 1, 'c': 1, 'b': 1, 'g': 1, 'f': 1,
                 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'n': 1, 'q': 1,

                 'p': 1, 't': 2, 'v': 1, 'x': 1, 'z': 1}

Notice some of the features of this dictionary. They keys are all single characters and the values are all integers. Moreover, there is one key for each letter of the alphabet. Plus there are keys for space and a punctuation mark, period (‘.’). There are 28 keys in all. In fact this dictionary stores the number of times each of these 28 characters occurs in a particular sentence of English. (You are welcome to guess which one, obviously a sentence that includes all 26 letters of the alphabet). In the cell below, write an expression that retrieves the value 5 from letter_counts. (There are two possible answers).

[answer here]

In the cell below write an expression that retrieves the integer associated with the key q from letter_counts.

[answer here]

3.5.4. Filling a Dictionary with information

Now let’s look at a more practical example of defining a dictionary.

from collections import Counter
Sentence = 'the quick brown fox jumped over the lazy yellow dog.'
letter_freqs = Counter()
for letter in Sentence:
    letter_freqs[letter] += 1
letter_freqs
Counter({' ': 9, 'e': 5, 'o': 5, 'l': 3, 'd': 2, 'h': 2, 'r': 2,
        'u': 2, 't': 2, 'w': 2, 'y': 2, '.': 1, 'a': 1, 'c': 1,
        'b': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1,
        'n': 1, 'q': 1, 'p': 1, 'v': 1, 'x': 1, 'z': 1})

This Counter named letter_freqs is defined in line 3 and filled with information in a for loop that begin on line 4 and ends on line 5. The variable Sentence is defined to be a string (line 2) and the for loop steps through each character of that string and adds 1 to its count in the dictionary (line 5). You may have noticed that the keys and counts in the Counter letter_freqs were the same as those in the dictionary letter_counts, defined in cell [5]. In fact a Counter is just a dictionary with some special features that make it easier to keep counts of things. We will be using Counters a lot to store simple counts. You should convince yourself the counts in letter_freqs are right (for example, there really is only one t in the sentence the quick brown fox jumoed over the lazy yellow dog.)

from collections import Counter
Sentence2 = 'The quick brown fox jumped over the lazy yellow dog.'
letter_freqs2 = Counter()
for letter in Sentence:
    letter_freqs2[letter] += 1
letter_freqs2

There is an important difference between the string Sentence and the string Sentence2. What is it? How is the difference reflected in letter_freqs2.

[Double click on this text and write your answer here.]