# CS61A Lab 6: Lists, Dictionaries, and Nonlocal

### Week 5, 2013

We have provided a starter file with skeleton code for the exercises in the lab. You can get it by typing this into your terminal:

```cp ~cs61a/lib/lab/lab06/shakespeare.py .
```

Don't forget the dot at the end!

### List Comprehensions

Last week, we covered lists, a powerful, mutable data structure that supports various operations including indexing and slicing. Similar to the generator expressions you've seen previously, lists can be created using a syntax called "list comprehension." Using a list comprehension is very similar to using the map or filter functions, but will return a list as opposed to a filter or map object.

```>>> a = [x+1 for x in range(10) if x % 2 == 0]
>>> a
[1, 3, 5, 7, 9]
```

To practice, write a function that adds two matrices together. The function should take in two 2D lists of the same dimensions.

```>>> add_matrices([[1, 3], [2, 0]], [[-3, 0], [1, 2]])
[[-2, 3], [3, 2]]
```

Now write a list comprehension that will create a deck of cards. Each element in the list will be a card, which is represented by a tuple containing the suit as a string and the value as an int.

Python also includes a powerful sort method. It can also take a key function that tells sort how to actually sort the objects. For more information, look at Python's documentation for the sort method. Note that sort is a stable sort. Now, use the sort method to sort a shuffled deck. It should put cards of the same suit together, and also sort each card in each suit in increasing value.

### Shakespeare and Dictionaries

First, let's talk about dictionaries. Dictionaries are simple an unordered set of key-value pairs. To create a dictionary, use the following syntax:

```>>> webster = {'Shawn': 'pineapple', 'Kim': 'blueberry'}
```

The curly braces denote the key-value pairs in your dictionary. Each key-value pair is separated by a coma, and for each pair the key appears to the left of the colon and the value appears to the right of the colon. You can retrieve values from your dictionary by 'indexing' using the key:

```>>> webster['Shawn']
'pineapple'

>>> webster['Kim']
'blueberry'
```

You can modify an entry for an existing key in the dictionary using the following syntax. Adding a new key follows the identical syntax!

```>>> webster['Shawn'] = 'strawberry'

>>> webster['Shawn']
'strawberry'

>>> webster['Carlton'] = 'donut' # new entry!

>>> webster['Carlton']
'donut
```

Now that you know how dictionaries work, we can move on to our next step - approximating the entire works of Shakespeare! We're going to use a bigram language model. Here's the idea: We start with some word - we'll use "The" as an example. Then we look through all of the texts of Shakespeare and for every instance of "The" we record the word that follows "The" and add it to a list, known as the successors of "The". Now suppose we've done this for every word Shakespeare has used, ever.

Let's go back to "The". Now, we randomly choose a word from this list, say "cat". Then we look up the successors of "cat" and randomly choose a word from that list, and we continue this process. This eventually will terminate in a period (".") and we will have generated a Shakespearean sentence!

The object that we'll be looking things up in is called a 'successor table', although really it's just a dictionary. The keys in this dictionary are words, and the values are lists of successors to those words.

A copy of the framework code is located in ~cs61a/lib/shakespeare.py - you should copy it to your directory

Here's an incomplete definition of the build_successors_table function. The input is a list of words (corresponding to a Shakespearean text), and the output is a successors table. (By default, the first word is a successor to '.'). See the example below:

```>>> def build_successors_table(tokens):
table = {}
prev = '.'
for word in tokens:
if prev in table:
"***FILL THIS IN***"

else:
"***FILL THIS IN***"

prev = word
return table

>>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.']

>>> table = build_successors_table(text)

>>> table
{'and': ['to'], 'We': ['came'], 'bad': ['guys'], 'pie': ['.'], ',': ['catch'], '.': ['We'], 'to': ['investigate', 'eat'], 'investigate': [','], 'catch': ['bad'], 'guys': ['and'], 'eat': ['pie'], 'came': ['to']}

```

Let's generate some sentences! Suppose we're given a starting word. We can look up this word in our table to find its list of successors, and then randomly select a word from this list to be the next word in the sentence. Then we just repeat until we reach some ending punctuation. (Note: to randomly select from a list, first make sure you import the Python random library with import random and then use the expression random.choice(my_list)) This might not be a bad time to play around with adding strings together as well. To get you started:

```>>> def construct_sent(word, table):
import random
result = ''
while word not in ['.', '!', '?']:
"**FILL THIS IN**"

return result + word
```

Great! Now all that's left is to run our functions with some actual code. The following snippet will return a list containing the words in all of the works of Shakespeare. (warning: do not try to print the return result of this function):

```>>> def shakespeare_tokens(path = 'shakespeare.txt', url = 'http://inst.eecs.berkeley.edu/~cs61a/fa11/shakespeare.txt'):
"""Return the words of Shakespeare's plays as a list"""
import os
from urllib.request import urlopen
if os.path.exists(path):
else:
shakespeare = urlopen(url)
```

Next, we probably want an easy way to refer to our list of tokens and our successors table. Let's make the following assignments:

```>>> tokens = shakespeare_tokens()

>>> table = build_successors_table(tokens)

```

Finally, let's define an easy to call utility function:

```>>> def sent():
return construct_sent('The', table)

>>> sent()
" The plebeians have done us must be news-cramm'd "

>>> sent()
" The ravish'd thee , with the mercy of beauty "

>>> sent()
" The bird of Tunis , or two white and plucker down with better ; that's God's sake "
```

### Nonlocal

Sometimes, we want to update a variable that is in a parent frame. However, that would normally create a new variable in our local frame, leaving the parent one untouched. Luckily, Python includes the nonlocal keyword, which tells Python that the designated variable exists in some parent frame and that we want to assign to that variable. Python will then use the previously bound variable in the closest parent frame that isn't the global frame. Predict the result of evaluating the following calls in the interpreter. Then try them out yourself!

```>>> def make_funny_adder(n):
if x == 'new':
nonlocal n
n = n + 1
else:
return x + n

>>> h(5)
...

>>> j(5)
...

>>> h('new')
>>> h(5)
...

>>> j(5)
...
```

Write a function make_fib that returns a function that returns the next Fibonacci number each time it is called. Examples:

```>>> fib = make_fib()

>>> fib()
1

>>> fib()
1

>>> fib()
2

>>> fib()
3

```