CS 111 w20 lecture 21 outline

1 Practice

For a string s, use a dictionary to count how many of each letter appear in the string

  • buggy version:
s = "how now brown cow"
char_counts = {}
for c in s:
    char_counts[c] += 1
print(char_counts)
  • fixed version:
s = "how now brown cow"
char_counts = {}
for c in s:
    if c in char_counts:
        char_counts[c] += 1
    else:
        char_counts[c] = 1
print(char_counts)

Reading in a file and counting word frequency:

fp = open("dickens.txt")
text = fp.read()
for c in "!\"#$%&()*+,-./:;<=>?@[\\]^_'{|}~":
    text = text.replace(c, " ")
words = text.split()
word_count = {}
for word in words:
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1
for word, count in word_count.items():
    print(word, count)

2 Choosing a Data Structure

  • choosing the right one can make your life much easier

3 Dictionary Mystery

rings_of_power = {
    "elves": 3,
    "dwarves": 7,
    "humans": 9
}
print("hobbits" in rings_of_power)
rings_of_power["Sauron"] = 1
acc = 0
for key in rings_of_power:
    acc += rings_of_power[key]
print("total rings:", acc)

4 Recursion

  • overall idea: something defined in terms of itself
def f(n):
    print("called f({})".format(n))
    if n <= 0:  # base case
        print("returning from base case")
        return
    f(n - 1)
    print("returning from n =", n)
    return
f(3)

4.1 Recursively Summing a List

def rec_sum(nums):
    if len(nums) == 0:
        return 0
    sum_of_the_rest = rec_sum(nums[1:])
    return nums[0] + sum_of_the_rest

4.2 Practice: Recursively Reverse a String

  • rev_str("cat") should return "tac"
  • identify a base case (empty string) and how you will divide the work between the current call and the recursive call
def rev_str(s):
    if len(s) == 0:
        return ""
    rest_reversed = rev_str(s[:-1])
    return s[-1] + rest_reversed

4.3 Linked List

  • a recursive data structure because each node of a linked list contains a reference to another linked list node
class ListNode:
    def __init__(self, val):
        self.val = val
        self.next_node = None
    def __repr__(self):
        s = "({})".format(self.val)
        if self.next_node != None:
            return "{} -> {}".format(s, repr(self.next_node))
        return s

def make_linked_list(nums):
    head = ListNode(nums[0])
    cur = head
    for num in nums[1:]:
        cur.next_node = ListNode(num)
        cur = cur.next_node
    return head

h = make_linked_list([3,2,6,7])
print(h)    

5 End of Class: Find a Final Project Partner