Berkeley Time!
+ 10 minutes
1
give me song recz: links.larynqi.com/recz
Discussion 03:
Recursion
February 10, 2022
Laryn Qi – larynqi@berkeley.edu – Lab 115L, 134L – Disc 134, 125
Announcements
Laryn Qi
Let’s talk about the midterm...
Point breakdown for CS 61A (from syllabus)
Read: 135 points in this class come from assignments/participation, 165 come from exams
If you get full credit on all non-exam stuff, you’d need:
Reassurances
Agenda
Laryn Qi
Recursion
Laryn Qi
Recursion
Laryn Qi
Recursion
RecursionError: maximum recursion depth exceeded
Laryn Qi
Recursion
Laryn Qi
Putting it all together
def factorial(n):
if n == 0 or n == 1:
return 1 # base case
else:
return n * factorial(n - 1)
Arms-length recursion
def factorial(n):
if n == 0 or n == 1:
return 1 # base case
else:
return n * (n - 1) * factorial(n - 2) # AHHHHHHHHH
Question 2:
Recursion ED
Laryn Qi
Question 1:
multiply
Laryn Qi
Q1 Multiply
Things to think about
Laryn Qi
Question 3:
Find the Bug
Laryn Qi
Question 4:
hailstone
Laryn Qi
Question 5:
merge
Laryn Qi
Helper Functions
Laryn Qi
Question 6:
is_prime
Laryn Qi
Tree Recursion
Laryn Qi
Tree Recursion
Laryn Qi
Example: Fibonacci Sequence
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Laryn Qi
Example: Count Partitions
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Laryn Qi
Tree Recursion Tips
Laryn Qi
Question 2.1:
count_stair_ways
Laryn Qi
Question 2.2:
count_k
Laryn Qi
Lists
Laryn Qi
Lists
Laryn Qi
List Examples
Basics
Slicing
lst[start:stop:step]
Laryn Qi
>>> lst = [1, 2, 3]
>>> lst[0]
1
>>> lst[2]
3
>>> lst[-1]
3
>>> lst[3]
ERROR
>>> len(lst)
3
>>> lst = [2, 0, 6, -1, 7]
>>> lst[1:4]
[0, 6, -1]
>>> lst[0:3:2]
[2, 6]
>>> lst[3:]
[-1, 7]
>>> lst[:]
[2, 0, 6, -1, 7]
>>> lst[10:]
[]
For Loops
Laryn Qi
def while_print_lst(lst):
index = 0
while index < len(lst):
print(lst[index])
index += 1
def for_print_lst(lst):
for elem in lst:
print(elem)
List Comprehensions
Laryn Qi
List Comprehensions
Laryn Qi
result = []
for elem in lst:
if elem > 3:
result = result + [elem + 1]
result = [elem + 1 for elem in lst if elem > 3]
Question 3.2:
even_weighted
Laryn Qi
35
Laryn Qi
Resources
Laryn Qi