cog sci 131 section

week 02/07/22

by shreshta (content) + yuan (slides)

agenda

  • homework feedback
  • recursion + context-free grammar
  • python trick: dictionaries 
  • go over hw3 prompts

homework feedback

  1. help us grade faster: start each solution on a separate page + include the question number🥺
  2. help yourself get partial credits: show us your code + comments in each solution, not just a graph 
  3. don't make us guess: use legends whenever necessary (multiple things in one graph) + label axes informatively 
  4. think like a designer: good data viz highlights major patterns in the model/data you want people to see 👉 "affordances" (make the intended function jump out)

recursion 

as a programming paradigm: using a function that calls itself until a specified condition is met

def fibonacci(n):
  "return the nth fibonacci number"
  # base case 1: f1 = 0
  if n == 1:
    return 0
  # base case 2: f2 = 1
  elif n == 2:
    return 1
  # if n > 2, call the function
  else:
    return fibonacci(n-1) + fibonacci(n-2)
F_n = F_{n-1} + F_{n-2}
F_1 = 0, F_2 = 1

base cases:

function:

in natural language:  "nonterminal" (e.g., S, NP, VP) is expanded into a set of terminals and nonterminals, which are themselves recursively expanded

[The boy] [believed [the clown laughed]].

DET + N

V

DET + N

V

NP

VP

S

dictionaries

useful data structure for hw3

# store word choices
nouns = {1: "Olivia", 2: "Liam", 3: "baker", 4: "telescope", 5: "animals"}

# initialize an empty dict 
sentence_freq = {}

# loop through sentences you generated
for s in sentences: 
  # if already in dict, increase count by 1
  if s in sentence_freq:
    sentence_freq[s] += 1
  # otherwise, start count at 1
  else:
    sentence_freq[s] = 1
    
    
  • a dictionary consists of a collection of key-value pairs 👉 values are accessed by keys: value = d[key] (indices don't work)
    • OrderedDict: remembers the order in which keys were added
    • defaultdict: return default values for missing keys
  • two use cases in hw2
    • store word choices
    • count sentence frequencies (prompt says use defaultdict, but ordinary dictionaries work)

hw3 prompts

cogsci131_02_07_section

By Yuan Meng

cogsci131_02_07_section

  • 136