Lab Check-in 1: Post-Midterm Check-In
Check-in questions and answers will be available after lab solutions are released.
Midterm
Q1: Exam Check-In
Note to academic interns: ask students how they feel about the midterm, and what they plan to do to do better on the final. Refer to Piazza @83 for how to have “the talk.”
Recursion
Q2: Recursive Hailstone
Recall the hailstone
function from hw01:
>>> def hailstone(n):
... length = 1
... while n != 1:
... print(n)
... if n % 2 == 0:
... n = n // 2
... else:
... n = n * 3 + 1
... length = length + 1
... print(n)
... return length
...
>>> a = hailstone(10)
10
5
16
8
4
2
1
>>> a
7
Ask students how they would make this a recursive function (on a high level--they'll probably need to do this recursively on a future assignment anyway).
Solution:
- Instead of incrementing length in a while-loop, make a recursive call
1 + hailstone(n * 3 + 1)
or1 + hailstone(n // 2)
. The1 +
represents the length increasing by one. - Set a base case (left as an exercise to the student)
Higher Order Functions
Q3: Parent Trap
What would Python print? Walk students through an environment diagram if they're stuck!
>>> def p(f):
... y = 1
... def r(y):
... f(y)
... return p(lambda x: print(y + x))
... return r
...
>>> y = 8
>>> f = p(lambda x: print(y + x))
>>> f = f(3)
______11
>>> f(7)
______10
<Function>