Download Lecture 5: Dictionaries and Recursion and more Schemes and Mind Maps Printing in PDF only on Docsity!
CS5001 / CS5003:
Intensive Foundations
of Computer Science
PDF of this presentation
Lecture 5: Dictionaries and RecursionLecture 5: Dictionaries and Recursion
Lecture 5: Practice!Lecture 5: Practice!
Let's practice a few topics that I think some students are still unclear about:
Looping a certain number of times
Printing a comma-separated list without the last comma
Breaking out of a while True loop
Practice 1: Write a loop to print a string,
s , X times (once per line), where X is the
length of the string. E.g., if the string is
" bats ":
bats
bats
bats
bats
Lecture 5: Practice!Lecture 5: Practice!
Let's practice a few topics that I think some students are still unclear about:
Looping a certain number of times
Printing a comma-separated list without the last comma
Breaking out of a while True loop
Practice 2: print a list, lst , one value at a time and comma separated, without the
last comma.
Lecture 5: Practice!Lecture 5: Practice!
Let's practice a few topics that I think some students are still unclear about:
Looping a certain number of times
Printing a comma-separated list without the last comma
Breaking out of a while True loop
Practice 2: print a list, lst , one value at a time and comma separated, without the
last comma.
solution
lst = ['cat', 'dog', 'bat', 'rat']
for i, val in enumerate(lst): if i == len(lst) - 1: print(val) else: print(f"{val}, ", end='')
solution
lst = ['cat', 'dog', 'bat', 'rat']
for v in lst[:-1]: print(f"{v}, ", end='') print(lst[-1])
solution
lst = ['cat', 'dog', 'bat', 'rat']
print(', '.join(lst))
Lecture 5: Practice!Lecture 5: Practice!
Let's practice a few topics that I think some students are still unclear about:
Looping a certain number of times
Printing a comma-separated list without the last comma
Breaking out of a while True loop
Practice 3: Print random numbers between 0 and 99 until two numbers in a row
are 90 or above (stop after the two numbers above 90 have been printed)
Solution
last = 0 while True: v = random.randint(0,99) print(v) if v > 90 and last > 90: break last = v
Lecture 5: Calculating the frequencies of letters in a sentenceLecture 5: Calculating the frequencies of letters in a sentence
Challenge: calculate the frequencies of letters in a sentence. For example, the
frequencies of letters in "my dog ate my homework" would be:
y : 2 : 4 d : 1 o : 3 g : 1 a : 1 t : 1 e : 2 h : 1 w : 1 r : 1 k : 1
There are two y's, four spaces, 1 d, three o's, etc.
How might you write a program to print out those frequencies?
Talk to your neighbor!
Lecture 5: Dictionaries: a better way!Lecture 5: Dictionaries: a better way!
So far in CS5001, we have talked about the following types of data:
integers, using int (e.g., 1, 5, -3, 18)
floating point numbers, using float (e.g., 1.3, 8.2, 14.5 )
strings, using either single or double quotes (e.g., "hello", "me",
'elephant' )
lists, using square brackets or list (e.g., a = [1, 3, 5, 23, 99] )
tuples, using parentheses (e.g., a = (1, 3, 5, 23, 99) )
Another very widely used data types is the dictionary , or dict.
A dict is a set of key value pairs. As an example, let's say you wanted to store
people's names with their phone numbers. You might have something like this:
Chris
Becky
Jenny
In this case, the keys are the
names, and the values are the
phone numbers. If you want a
value, you ask for it by the key.
Lecture 5: DictionariesLecture 5: Dictionaries
In Python, we can create a dictionary as follows:
Chris
Becky
Jenny
phonebook = {'Chris' : '685-6587', 'Becky' : '434-2221', 'Jenny' : '867-5309'}
To get a value for a key, we use square brackets:
>>> phonebook['Chris'] '685-6587' >>> phonebook['Becky'] '434-2221' >>> phonebook['Jenny'] '867-5309'
Lecture 5: DictionariesLecture 5: Dictionaries
Dictionaries are useful for many things. Take a look at this program:
sentence = "the quick brown fox jumps over the lazy dog" frequencies = {} for c in sentence: if c not in frequencies: frequencies[c] = 1 else: frequencies[c] += 1 for key, value in frequencies.items(): print(f"{key} : {value}")
What does it do?
Lecture 5: DictionariesLecture 5: Dictionaries
Dictionaries are useful for many things. Take a look at this program:
sentence = "the quick brown fox jumps over the lazy dog" frequencies = {} for c in sentence: if c not in frequencies: frequencies[c] = 1 else: frequencies[c] += 1 for key, value in frequencies.items(): print(f"{key} : {value}")
This program figures out how many of each letter are in the sentence! Output:
t : 2 h : 2 e : 3 : 8 q : 1 u : 2 i : 1 c : 1 k : 1 b : 1 r : 2 o : 4 w : 1
n : 1 f : 1 x : 1 j : 1 m : 1 p : 1 s : 1 v : 1 l : 1 a : 1 z : 1 y : 1 d : 1 g : 1
This is exactly the same program as we wrote
earlier, except much less messy. Notice we simply
added a new character (as key) to the dictionary if
the character wasn't already in the dictionary, and
if it was in the dictionary, we simply updated the
count.
Lecture 5: DictionariesLecture 5: Dictionaries
Here is the function using lists. We convert the result to a dictionary at the end to
make the return value of both functions the same:
def get_word_freqs_list(filename): word_strings = [] word_frequencies = [] word_count = 0 with open(filename) as f: for line in f: line = ''.join(ch for ch in line if ch.isalnum() or ch == ' ').lower() words = line.split(' ') for word in words: word_count += 1 if word_count % 1000 == 0: print(f"Found {word_count} words.") if word not in word_strings: word_strings.append(word) word_frequencies.append(1) else: word_frequencies[word_strings.index(word)] += 1 return dict(zip(word_strings, word_frequencies))
The functions aren't that different, so you might be wondering why we would use
one or the other.
Lecture 5: DictionariesLecture 5: Dictionaries
Here is the driver for the function. Notice that we can easily test both functions by
uncommenting / commenting two lines:
if name == "main":
word_freqs = get_word_freqs_dict(BOOK_FILE)
word_freqs = get_word_freqs_list(BOOK_FILE) print(f"There are {len(word_freqs)} unique words in {TITLE}") while True: word = input("Word? ").lower() if word in word_freqs: print(f"'{word}' is found {word_freqs[word]} time(s) in {TITLE}")
Let's go see the code and run it...
Lecture 5: DictionariesLecture 5: Dictionaries
If you want to get a list of just the keys or just the values in a dictionary, you can do
it like this:
>>> phonebook = {'Chris': '685-6587', 'Jenny': '867-5309', 'John': '867-5309', 'Becky': '434-2221'} >>> phonebook.keys() dict_keys(['Chris', 'Jenny', 'John', 'Becky']) >>> phonebook.values() dict_values(['685-6587', '867-5309', '867-5309', '434-2221']) >>>
1 2 3 4 5 6
Note: these are actually not lists, but you can treat them as lists. You could also
turn them into lists as follows:
>>> phonebook = {'Chris': '685-6587', 'Jenny': '867-5309', 'John': '867-5309', 'Becky': '434-2221'} >>> list(phonebook.keys()) ['Chris', 'Jenny', 'John', 'Becky'] >>> list(phonebook.values()) ['685-6587', '867-5309', '867-5309', '434-2221'] >>>
1 2 3 4 5 6
Remember -- you won't get the keys or values in any particular order (though both
lists will be in the same order). Dictionaries are not sorted!
Also notice above that the keys are always unique, but the values don't have to be
unique (and there are two '867-5309' values in this example).
Lecture 5: DictionariesLecture 5: Dictionaries
Similar to lists and tuples, dicts can hold different types as either their keys or
their values. Frequently, we will want to keep a dict of string keys, with various
types for their values. Example:
actor_details = { 'first_name' : 'Scarlett', 'last_name' : 'Johansson', 'movies': ['Lost in Translation', 'Girl with a Pearl Earring', 'The SpongeBob SquarePants Movie', 'The Avengers'], 'age' : 34, 'birthday' : 'November 22, 1984', }
1 2 3 4 5 6 7 8
Note that we have nicely formatted this -- one key/value pair per line (except
when the lines are too long).
Notice as well that the values are different types -- we have strings, lists, and ints
as values.
Finally -- this may seem weird, but we can also end the last item with a comma,
even though there aren't more items. This is allowed by Python, and something
you will see often (you can also leave off the trailing comma).