name: inverse layout: true class: center, middle, inverse --- # CS 61A – Discussion 2 ## Allen Guo ## http://aguo.us/cs61a --- layout: false class: center, middle # Quiz --- layout: false # Announcements - Hog due today - Lab 2 due tomorrow - Homework 3 due Tuesday - Midterm 1 next Thursday (8-10pm) --- class: center, middle # Survey ## http://x.aguo.us --- class: center, middle, inverse # Worksheet --- # Environment Diagrams - How do we perform lookup? - How do we evaluate a primitive expression? - How do we evaluate a call expression? - What is the parent frame of a function? .footnote[Source: [Environment Diagram Party Slides](https://docs.google.com/presentation/d/1pKado1dzDzJaAAoTAkovQeMB3YwK5uo6BNenCQgH8xI/edit?usp=sharing)] --- # Closure Example ```python def f(): x = 1 def g(y): return x + y x = 2 return g g = f x = 3 h = f() print(h(0)) ``` -- - Environment diagram demo: [Python Tutor](http://www.pythontutor.com/visualize.html#code=def%20f%28%29%3A%0A%20%20%20%20x%20%3D%201%0A%20%20%20%20def%20g%28y%29%3A%0A%20%20%20%20%20%20%20%20return%20x%20%2B%20y%0A%20%20%20%20x%20%3D%202%0A%20%20%20%20return%20g%0Ag%20%3D%20f%0Ax%20%3D%203%0Ah%20%3D%20f%28%29%0Aprint%28h%280%29%29&cumulative=true&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false) -- - The function with intrinsic name `g` is a closure - What variable is "captured" or "closed over" by `g`? --- # Recursion Done Wrong ```python def f(x): return f(x) ``` -- - What's wrong with it? -- - No base case - The recursive case doesn't make the problem smaller --- # Recursion - Three things you need: -- - One or more base cases. - One or more ways to make the problem smaller. - One or more ways to solve the "big" problem using the "small" problem. --- # Recursion Done Right ```python def sum_up(n): if n == 0: return 0 return n + sum_up(n - 1) ``` - What does this function do? - Where's the base case? - Where do we make the problem smaller? - Where do we use the smaller problem to solve the bigger problem?