0% found this document useful (0 votes)
26 views

Mit6 100l f22 Lec16

Uploaded by

fukchuntse40
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Mit6 100l f22 Lec16

Uploaded by

fukchuntse40
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

RECURSION ON NON-

NUMERICS
(download slides and .py files to follow along)
6.100L Lecture 16
Ana Bell

1
REVIEW OF RECURSION FROM
LAST LECTURE, WITH AN EXAMPLE

 Fibonacci numbers (circa 1202)


 Leonardo of Pisa (aka Fibonacci) modeled
rabbits mating (under certain assumptions) as
a Fibonacci sequence
Month Females
 newborn pair of rabbits (one female, one male)
are put in a pen 1 1
 rabbits mate at age of one month 2 1
 rabbits have a one month gestation period
3 2
 assume rabbits never die, that female always
produces one new pair (one male, one female) 4 3
each month from its second month on
5 5
 females(n) = females(n-1) + females(n-2) 6 8
7 13
Females alive in Every female alive at
month n-1 month n-2 will produce
one2 female in month n
6.100L Lecture 16
FIBONACCI

 Base cases:
 Females(1) = 1
 Females(2) = 1
 Recursive case
 Females(n) = Females(n-1) + Females(n-2)

6.100L Lecture 16
FIBONACCI RECURSIVE CODE
(MULTIPLE BASE CASES)
def fib(x):
if x == 1 or x == 2:
return 1
else:
return fib(x-1) + fib(x-2)

Two base cases


 Calls itself twice
 But! It has to go to the base case of the first fib call before
completing the second fib call
4

6.100L Lecture 16
HIGH-LEVEL VIEW OF def fib(x):
FIBONACCI with if x == 1 or x == 2:
return 1
RECURSION else:
PYTHON TUTOR LINK return fib(x-1) + fib(x-2)

Fib(6)

Fib(5) Fib(4)

Fib(4) Fib(3) Fib(3) Fib(2)

Fib(3) Fib(2) Fib(2) Fib(1) Fib(2) Fib(1)

Fib(2) Fib(1)

6.100L Lecture 16
INEFFICIENT FIBONACCI
fib(x) = fib(x-1) + fib(x-2)

Fib(6)

Fib(5) Fib(4)

Fib(4) Fib(3) Fib(3) Fib(2)

Fib(3) Fib(2) Fib(2) Fib(1) Fib(2) Fib(1)

Fib(2) Fib(1)

 Recalculating the same values many times!


 Could keep track of already calculated values
6

6.100L Lecture 16
FIBONACCI WITH
MEMOIZATION
Python Tutor LINK
def fib_efficient(n, d):
if n in d:
return d[n]
else:
ans = fib_efficient(n-1, d) + fib_efficient(n-2, d)
d[n] = ans
return ans

d = {1:1, 2:1}
print(fib_efficient(6, d))

 Do a lookup first in case already calculated the value


 Modify dictionary as progress through function calls
7

6.100L Lecture 16
EFFICIENT FIBONACCI CHECKS the DICT FIRST
n fib(n)

Fib(6) 1 1
2 1
Fib(5) Fib(4) 3 2
4 3
Fib(4) Fib(3)
5 5
6 8
Fib(3) Fib(2)

Fib(2) Fib(1)

 No more recalculating, just check the dict before calculating!


 Add to the dict so we can look it up next time we see it
8

6.100L Lecture 16
EFFICIENCY GAINS

 Calling fib(34) results in 11,405,773 recursive calls to the


procedure
 Calling fib_efficient(34) results in 65 recursive calls to
the procedure
 Using dictionaries to capture intermediate results can be very
efficient
 But note that this only works for procedures without side
effects (i.e., the procedure will always produce the same result
for a specific argument independent of any other computations
between calls)
9

6.100L Lecture 16
A MORE PRACTICAL EXAMPLE
WHAT ARE ALL THE WAYS YOU CAN MAKE A SCORE OF x IN BASKETBALL?

def score_count(x):
""" Returns all the ways to make a score of x by adding
1, 2, and/or 3 together. Order doesn't matter. """
if x == 1:
return 1
elif x == 2:
return 2
elif x == 3:
return 3
else:
return score_count(x-1)+score_count(x-2)+score_count(x-3)

In basketball you can make a basket worth 1, 2, or 3 points


 Base cases: 3 of them!
 You can make a score of 1 with 1+0 (that’s 1 way)
 You can make a score of 2 with 1+1 or 2+0 (that’s 2 ways)
 You can make a score of 3 with 1+1+1 or 2+1 or 3+0 (that’s 3 ways)
10

6.100L Lecture 16
A MORE PRACTICAL EXAMPLE: PYTHON TUTOR LINK
WHAT ARE ALL THE WAYS YOU CAN MAKE A SCORE OF x IN BASKETBALL?

def score_count(x):
""" Returns all the ways to make a score of x by adding
1, 2, and/or 3 together. Order doesn't matter. """
if x == 1:
return 1
elif x == 2:
return 2
elif x == 3:
return 3
else:
return score_count(x-1)+score_count(x-2)+score_count(x-3)

 Recursive step: Let future function calls do the work down until base cases
 Ways to make a score of x means you could have made:
a score of (x-1) or a score of (x-2) or a score of (x-3)
 If you make a score of x-1 you can just add 1 to it to make the score of x.
 If you make a score of x-2 you can just add 2 to it to make the score of x.
 If you make a score of x-3 you can just add 3 to it to make the score of x.
11

6.100L Lecture 16
HIGH-LEVEL VIEW def score_count(x):
if x == 1:

of score_count
return 1
elif x == 2:
return 2
elif x == 3:
return 3
else:
return score_count(x-1)+score_count(x-2)+score_count(x-3)

score(6)

score(5) score(4) score(3)

score(2)
score(4) score(3)score(2) score(3) score(2)

score(3) score(1)
score(2)

12

6.100L Lecture 16
SUM of LIST ELEMENTS

13

6.100L Lecture 16
LISTS ARE NATURALLY RECURSIVE

def total_iter(L):
result = 0
for e in L:
result += e
return result

test = [30, 40, 50]


print(total_iter(test))

14

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Find sum of this original list


15

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 L[0] + sum of the new list


16

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Solve the same problem, slightly changed (its length is smaller)


17

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 L[0] + sum of the new list


18

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Solve the same problem again, slightly changed


19

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 L[0] + sum of the new list


20

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Keep repeating, decreasing until a base case


21

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Keep repeating, decreasing until a base case


22

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 The base case


23

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Pass the sum back up the chain


24

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Pass the sum back up the chain


25

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Pass the sum back up the chain


26

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Pass the sum back up the chain


27

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Pass the sum back up the chain


28

6.100L Lecture 16
VISUALIZING LISTS as RECURSIVE

10 20 30 40 50 60

 Pass the sum back up the chain


29

6.100L Lecture 16
SUM of LIST ELEMENTS:
the PIECES

def total_recur(L): • Base case


if • Recursive step

else:

test = [30, 40, 50]


print(total_recur(test))

30

6.100L Lecture 16
SUM of LIST ELEMENTS:
the BASE CASE (one option)

def total_recur(L): • What is the base case?


if L == []: • One option:
return 0 An empty list has sum 0
else:

test = [30, 40, 50]


print(total_recur(test))

31

6.100L Lecture 16
SUM of LIST ELEMENTS:
the BASE CASE (another option)

def total_recur(L): • What is the base case?


if len(L) == 1: • Another option:
return L[0] A list with one element
else: has a sum of that one
element
• For example:
L = [50]
test = [30, 40, 50] Returns:
print(total_recur(test)) 50

32

6.100L Lecture 16
SUM of LIST ELEMENTS:
the RECURSIVE STEP

def total_recur(L): • What is the recursive step?


if len(L) == 1: • Need to get to the base case
return L[0] somehow
else: • Let’s look at elements one
return L[0] + # something at a time
• Extract the first one and
test = [30, 40, 50] grab its value
print(total_recur(test)) • For example:
L = [30,40,50]
Returns:
30 + <something>

33

6.100L Lecture 16
SUM of LIST ELEMENTS
RECURSIVE STEP will EVENTUALLY END

def total_recur(L): • What is the recursive step?


if len(L) == 1: • The function call finds the
return L[0] sum of the remaining list
else: elements
return L[0] + total_recur(L[1:]) • For example:
L = [30,40,50]
Returns:
test = [30, 40, 50] 30 + total_recur([40,50])
print(total_recur(test))

34

6.100L Lecture 16
SUM of LIST ELEMENTS:
TAKEAWAYS, Python Tutor LINK

def total_recur(L): • Notice:


if len(L) == 1: • Every case in the function
return L[0] returns something that is
else: the same type
return L[0] + total_recur(L[1:]) • Base case returns an int
• Recursive step returns an int

test = [30, 40, 50]


• We need to trust that the
recursive calls eventually do
print(total_recur(test)) the right thing

35

6.100L Lecture 16
YOU TRY IT!
 Modify the code we wrote to return the total length of all strings
inside L:
def total_len_recur(L):
if len(L) == 1:
return _______
else:
return __________________

test = ["ab", "c", "defgh"]


print(total_recur(test)) # prints 8

36

6.100L Lecture 16
LOOKING for an
ELEMENT in a LIST

37

6.100L Lecture 16
ANOTHER EXAMPLE:
Is an ELEMENT in a LIST?
(careful with this implementation)
def in_list(L, e): • Let’s start by following the
if len(L) == 1: same pattern as the prev
return L[0] == e example
else: • Base case is when we have
return in_list(L[1:], e) one element
• Check if it’s the one we are
looking for
• Recursive step looks at the
remaining elements
• Grab the list from index 1
onward and look for e in it

38

6.100L Lecture 16
ANOTHER EXAMPLE:
Is an ELEMENT in a LIST?
(careful with this implementation) Python Tutor
def in_list(L, e): • Test it out
if len(L) == 1: • test = [2,5,8,1] and e=1
return L[0] == e gives True
• ok
else:
return in_list(L[1:], e)
• test = [2,1,5,8] and e=1
gives False
test = [2,5,8,1] • Not ok!
print(in_list(test, 1))
• It checks only if the last
test = [2,1,5,8]
elem is the one we are
looking for!
print(in_list(test, 1))
39

6.100L Lecture 16
ANOTHER EXAMPLE:
Is an ELEMENT in a LIST?
(fix the implementation)
def in_list(L, e): • Still want to look at
if len(L) == 1: elements one at a time
return L[0] == e • Need to check whether the
else: element we extracted is the
# Check the first element one we are looking for at
each function call
# before looking in the rest

return in_list(L[1:], e)

40

6.100L Lecture 16
ANOTHER EXAMPLE:
Is an ELEMENT in a LIST?
(fix the implementation)
def in_list(L, e): • Still want to look at
if len(L) == 1: elements one at a time
return L[0] == e • Add the check in the
else: recursive step, before
if L[0] == e: checking the rest of the list.
return True
else:
return in_list(L[1:], e)

41

6.100L Lecture 16
ANOTHER EXAMPLE:
Is an ELEMENT in a LIST?
(test the implementation) Python Tutor LINK
def in_list(L, e): • Test it now
if len(L) == 1: • test = [2,5,8,1] and e=1
return L[0] == e gives True
else: • ok
if L[0] == e: • test = [2,1,5,8] and e=1
return True gives True
else: • ok
return in_list(L[1:], e) • test = [2,5,8] and e=1 gives
False
• ok

42

6.100L Lecture 16
ANOTHER EXAMPLE:
Is an ELEMENT in a LIST?
(improve the implementation)
def in_list(L, e): • Two cases that return L[0]
if len(L) == 0: • Add case when L is empty
return False
• Simplify the code to check
elif L[0] == e: the first element as another
return True base case
else:
return in_list(L[1:], e)

43

6.100L Lecture 16
BIG IDEA
Each case (base cases, recursive step)
must return the same
type of object.
Remember that function returns build upon each other!
If the base case returns a bool and the recursive step returns
an int, this gives a type mismatch error at runtime.

44

6.100L Lecture 16
FLATTEN a LIST with
ONLY ONE LEVEL of LIST
ELEMENTS

45

6.100L Lecture 16
FLATTEN a LIST CONTAINING LISTS of ints
e.g. [[1, 2],[3, 4],[9, 8, 7]]
gives [1, 2, 3, 4, 9, 8, 7]
def flatten(L): • Base case
if len(L) == 1: • There is only one element
in L
else: • For example:
[[2,3,4]]

46

6.100L Lecture 16
FLATTEN a LIST CONTAINING LISTS of ints
e.g. [[1, 2],[3, 4],[9, 8, 7]]
gives [1, 2, 3, 4, 9, 8, 7]
def flatten(L): • Base case
if len(L) == 1: • Return that element
return L[0]
• For example:
else: [[2,3,4]]
Returns:
[2,3,4]

47

6.100L Lecture 16
FLATTEN a LIST CONTAINING LISTS of ints
e.g. [[1, 2],[3, 4],[9, 8, 7]]
gives [1, 2, 3, 4, 9, 8, 7]
def flatten(L): • Recursive step
if len(L) == 1: • Recall that + between two
return L[0] lists concatenates the
else: elements into a new list
return L[0] + #something • Make a new list containing
the first element and…

48

6.100L Lecture 16
FLATTEN a LIST CONTAINING LISTS of ints
e.g. [[1, 2],[3, 4],[9, 8, 7]]
gives [1, 2, 3, 4, 9, 8, 7]
Python Tutor LINK
def flatten(L): • Recursive step
if len(L) == 1: • … flatten the rest of the
return L[0] remaining list
else: • For example:
return L[0] + flatten(L[1:]) [[1,2],[3,4],[9,8,7]]
Returns:
[1,2] +
flatten([[3,4], [9,8,7]])

49

6.100L Lecture 16
YOU TRY IT!
 Write a recursive function according to the specs below.
def in_list_of_lists(L, e):
"""
L is a list whose elements are lists containing ints.
Returns True if e is an element within the lists of L
and False otherwise.
"""
# your code here

test = [[1,2], [3,4], [5,6,7]]


print(in_list_of_lists(test, 0)) # prints False
test = [[1,2], [3,4], [5,6,7]]
print(in_list_of_lists(test, 3)) # prints True

50

6.100L Lecture 16
WHEN to USE RECURSION

 So far you should have some intuition


for how to write recursive functions
 The problem is that so far you’ve been
writing recursive version of functions
that are usually easier to implement
WITHOUT recursion :(
 So why learn recursion?
 Some problems are very difficult to solve
with iteration

51

6.100L Lecture 16
INTUITION for WHEN to use
RECURSION
 Remember when we learned while loops?
 Remember when we tried to write a program that kept asking
the user which way to go in the Lost Woods of Zelda?
 We did not know ahead of time how many times we needed to
loop! (aka how many levels of if/else we needed)
 While loops kept iterating as long as some condition held true.
© Nintendo. All rights reserved. This content is excluded from our
Creative Commons license. For more information, see
if <exit right>: https://ocw.mit.edu/help/faq-fair-use/
<set background to woods_background>
if <exit right>:
<set background to woods_background>
if <exit right>:
<set background to woods_background>
and so on and on and on...
else:
<set background to exit_background>
else:
<set background to exit_background>
else:
<set background to exit_background> 52

6.100L Lecture 16
INTUITION for WHEN to use
RECURSION
 In the list recursion examples so far, we knew how many levels
we needed to iterate.
 Either look at elems directly or in one level down
 But lists can have elements that are lists, which can in turn
have elements that are lists, which can in turn have elements
that are lists, etc.
 How can we use iteration to do these checks? It’s hard.
for i in L:
if type(i) == list:
for j in i:
if type(j) == list:
for k in j:
if type(k) == list:
# and so on and on
else:
# do what you need to do
else:
# do what you need to do
else:
# do what you need to do
53
# done with the loop over L and all its elements
6.100L Lecture 16
PROBLEMS that are NATURALLY
RECURSIVE
 A file system
 Order of operations in a calculator
 Scooby Doo gang searching a haunted castle
 Bureaucracy

54

6.100L Lecture 16
LET’S SEE HOW TO GO FROM ONE
LEVEL to MANY LEVELS (RECURSIVELY)

 Example: reverse a list’s elements


 How to break up the problem into a smaller version of your
same problem?

1 2 3 4

55

6.100L Lecture 16
LET’S SEE HOW TO GO FROM ONE
LEVEL to MANY LEVELS (RECURSIVELY)

 Example: reverse a list’s elements


 How to break up the problem into a smaller version of your
same problem?

2 3 4 1

56

6.100L Lecture 16
LET’S SEE HOW TO GO FROM ONE
LEVEL to MANY LEVELS (RECURSIVELY)

 Example: reverse a list’s elements


 How to break up the problem into a smaller version of your
same problem?

2 3 4 1

57

6.100L Lecture 16
LET’S SEE HOW TO GO FROM ONE
LEVEL to MANY LEVELS (RECURSIVELY)

 Example: reverse a list’s elements


 How to break up the problem into a smaller version of your
same problem?

3 4 2 1

58

6.100L Lecture 16
LET’S SEE HOW TO GO FROM ONE
LEVEL to MANY LEVELS (RECURSIVELY)

 Example: reverse a list’s elements


 How to break up the problem into a smaller version of your
same problem?

3 4 2 1

59

6.100L Lecture 16
LET’S SEE HOW TO GO FROM ONE
LEVEL to MANY LEVELS (RECURSIVELY)

 Example: reverse a list’s elements


 How to break up the problem into a smaller version of your
same problem?

4 3 2 1

60

6.100L Lecture 16
LET’S SEE HOW TO GO FROM ONE
LEVEL to MANY LEVELS (RECURSIVELY)

 Example: reverse a list’s elements


 How to break up the problem into a smaller version of your
same problem?

4 3 2 1

61

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
TOP-LEVEL ONLY

def my_rev(L): • Base case


if len(L) == 1:

else:

62

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
TOP-LEVEL ONLY

def my_rev(L): • Base case


if len(L) == 1: • Reversing a list with one
return L element is just that list.
else:

63

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
TOP-LEVEL ONLY

def my_rev(L): • Recursive step


if len(L) == 1: • Move element at index 0 to
return L the end.
else: • Equivalent to
return <something> + [L[0]] concatenating something
with that element
• For example:
[10,20,30,40]
Returns:
<something> + [10]

64

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
TOP-LEVEL ONLY

def my_rev(L): • Recursive step


if len(L) == 1: • Solve the same problem,
return L but on the list containing
else: all elements except the
return my_rev(L[1:]) + [L[0]] first one
• For example:
[10,20,30,40]
Returns:
my_rev([20,30,40]) + [10]

65

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
TOP-LEVEL ONLY
Python Tutor LINK
def my_rev(L): • Test it
if len(L) == 1: test = [1, 2, "abc"]

return L # prints
['abc', 2, 1]
else:
return my_rev(L[1:]) + [L[0]] test = [1,['d'],['e',['f', 'g']]]
# prints this, notice it
# just reverses top-level elems
test = [1, 2, "abc"] [['e', ['f', 'g']], ['d'], 1]

print(my_rev(test))

test = [1,['d'],['e',['f', 'g']]]


print(my_rev(test))
66

6.100L Lecture 16
ALL ELEMENTS GET REVERSED

 Example: reverse all elements in all sublists


 Need to know whether we have an element or a list
 Elements are put at the end, lists are reversed themselves

[1, 2] 3 4 [[5,6], [7,8]]

67

6.100L Lecture 16
ALL ELEMENTS GET REVERSED

 If it’s a list,

3 4 [[5,6], [7,8]] [1,2]

68

6.100L Lecture 16
ALL ELEMENTS GET REVERSED

 If it’s a list,

3 4 [[5,6], [7,8]] [2,1]

69

6.100L Lecture 16
ALL ELEMENTS GET REVERSED

 If it’s not a list

4 [[5,6], [7,8]] 3 [2,1]

70

6.100L Lecture 16
ALL ELEMENTS GET REVERSED

 And so on.

[[5,6], [7,8]] 4 3 [2,1]

71

6.100L Lecture 16
ALL ELEMENTS GET REVERSED

 Lists within lists get reversed each

[[7,8], [5,6]] 4 3 [2,1]

72

6.100L Lecture 16
ALL ELEMENTS GET REVERSED

 Lists within lists get reversed each

[[7,8], [6,5]] 4 3 [2,1]

73

6.100L Lecture 16
ALL ELEMENTS GET REVERSED

 Lists within lists get reversed each

[[8,7], [6,5]] 4 3 [2,1]

74

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
ALL ELEMENTS GET REVERSED

def deep_rev(L): • Base case is NOT the same


if len(L) == 1: • A single element can either
if type(L[0]) != list: be a
# do something • Non-list:
else:
• List:
# do something

75

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
ALL ELEMENTS GET REVERSED

def deep_rev(L): • Base case is NOT the same


if len(L) == 1: • A single element can either
if type(L[0]) != list: be a
return L • Non-list: it’s just the list
itself, like before
else:
• List:
# do something

76

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
ALL ELEMENTS GET REVERSED

def deep_rev(L): • Base case is NOT the same


if len(L) == 1: • A single element can either
if type(L[0]) != list: be a
return L • Non-list: it’s just the list
itself, like before
else:
• List: Must reverse it!
return [deep_rev(L[0])]

77

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
ALL ELEMENTS GET REVERSED

def deep_rev(L): • Recursive step


if len(L) == 1: • Extract the first element. It
if type(L[0]) != list: can either be a
return L • Non-list:
else:
return [deep_rev(L[0])]
else: • List:
if type(L[0]) != list:
# do something
else:
# do something
78

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
ALL ELEMENTS GET REVERSED

def deep_rev(L): • Recursive step


if len(L) == 1: • Extract the first element. It
if type(L[0]) != list: can either be a
return L • Non-list: reverse the
remaining elements and
else:
concatenate the result with
return [deep_rev(L[0])] the first element
else: • List:
if type(L[0]) != list:
return deep_rev(L[1:]) + [L[0]]
else:
# do something
79

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
ALL ELEMENTS GET REVERSED

def deep_rev(L): • Recursive step


if len(L) == 1: • Extract the first element. It
if type(L[0]) != list: can either be a
return L • Non-list: reverse the
remaining elements and
else:
concatenate the result with
return [deep_rev(L[0])] the first element
else: • List: reverse the remaining
elements and concatenate
if type(L[0]) != list: the result with the first
return deep_rev(L[1:]) + [L[0]] element reversed (it’s a list!)
too
else:
return deep_rev(L[1:]) + [deep_rev(L[0])]
80

6.100L Lecture 16
REVERSE a LIST of ELEMENTS:
ALL ELEMENTS GET REVERSED
CLEANED UP CODE
def deep_rev(L): • Extract out the empty list
if L == []: • Extract out L[0]
return []
elif type(L[0]) != list:
return deep_rev(L[1:]) + [L[0]]
else:
return deep_rev(L[1:]) + [deep_rev(L[0])]

81

6.100L Lecture 16
BIG IDEA
Recursion procedure from this
lecture can be applied to any
indexable ordered sequence.
The same idea will work on problems involving strings.
The same idea will work on problems involving tuples.

82

6.100L Lecture 16
MAJOR RECURSION TAKEAWAYS

 Most problems are solved more intuitively with iteration


 We show recursion on these to:
 Show you a different way of thinking about the same problem (algorithm)
 Show you how to write a recursive function (programming)
 Some problems have nicer solutions with recursion
 If you recognize solving the same problem repeatedly, use recursion
 Tips
 Every case in your recursive function must return the same type of thing
i.e. don’t have a base case return []
and a recursive step return len(L[0])+recur(L[1:])
 Your function doesn’t have to be efficient on the first pass
 It’s ok to have more than 1 base case
 It’s ok to break down the problem into many if/elifs
 As long as you are making progress towards a base case recursively
83

6.100L Lecture 16
YOU TRY IT!
 I added many practice recursion questions in the .py file
associated with this lecture, to prep for the quiz.
 1) An exercise to implement a recursive function (no lists within
lists etc.)
 2) An exercise to implement a recursive function (with lists
within lists within lists etc.)
 3) Three buggy recursion implementations to fix.

84

6.100L Lecture 16
MITOpenCourseWare
https://ocw.mit.edu

6.100L Introduction to Computer Science and Programming Using Python


Fall 2022

For information about citing these materials or our Terms ofUse,visit: https://ocw.mit.edu/terms.

85

You might also like