Lab: Basic Recursion
Exercise 1
Consider the following function select_strings
that extracts the strings out of a list.
def select_strings(lst):
"""Returns a list of all the strings in lst"""
# If lst contains zero elements...
if len(lst) == 0:
# Then there are no strings to select, so return empty list
return []
# If the type of the first element is a string...
elif type(lst[0]) == str:
# Return it, along with any other strings we find in the
# rest of the list
return [lst[0]] + select_strings(lst[1:])
# If the type of the first element is NOT a string...
else:
# Then return just the strings in the rest of the list
return select_strings(lst[1:])
a. Save this code in a file and import it into the REPL.
b. Discuss the code with your partner and make sure you understand each of the components.
c. Execute the code on a variety of inputs and ensure that it is extracting out the strings as expected.
(Optional) You may find it helpful to create a main function that calls the function on a couple inputs and watch it execute using the debugger pudb3
.
Exercise 2
Consider the following function is_palindrome
that checks if a string is the same if read both forwards and backwards. An example of a palindrome is “civic”.
def is_palindrome(s):
if len(s) <= 1:
return True
# Checks if the first character is equal to the last
# and checks if the substring excluding the first and
# last characters is also a palindrome
return (s[0] == s[-1]) and is_palindrome(s[1:-1])
a. Save this code in a file and import it into the REPL.
b. Discuss the code with your partner and make sure you understand each of the components. (For example, why don’t we need an else:
clause before the second return statement?)
c. Execute the code on a variety of inputs and ensure that it is working as expected.
d. Add the following line of code immediately before the if
statement (just after the declaration of the function):
print('is_palindrome("' + s + '")')
e. Execute is_palindrome
on a variety of strings and watch how it recurses.
(Optional) You may find it helpful to create a main function that calls the function on a couple inputs and watch it execute using the debugger pudb3
.
Exercise 3
Using a similar technique to how we wrote factorial
, write a function called termial(n)
that computes the sum of the first n
natural numbers. For example,
>>> termial(5)
15
…because 15 = 1 + 2 + 3 + 4 + 5
.
Exercise 4
Using a technique similar to exercise 2, write a recursive function called reverse(lst)
that takes in a list as a parameter and returns a new list that has the elements in the reverse order. Thus, reverse([100, 200, 300])
returns the list [300, 200, 100]
.