Exercises for Lesson 25
Exercise 1: Summing numbers, recursively
Consider the following function, which returns the sum of the numbers from 1 to n
.
def recursiveSum(n):
# Base case
if n == 1:
return 1
# Recursive case
return n + recursiveSum(n-1)
What is the output for recursiveSum(6)
? It may help to a call tree showing the recursive function calls.
Exercise 2: Reversing a string, recursively
Write a function that returns the reverse of a string. It should use a recursive approach.
def recursiveReverse(s):
return "" # TODO
For example, if we have mystr = "cheddar"
, then recursiveReverse(mystr)
should return "raddehc"
.
Exercise 3: Finding vowels in a string, recursively
Write a function that returns a list containing only the vowels in a given string (assumed to be all lowercase). It should use a recursive approach.
def recursiveVowels(s):
return [] # TODO
For example, if we have mystr = "elephant"
, then recursiveVowels(mystr)
should return ['e', 'e', 'a']
.
Exercise 4: Finding anagrams of a string, recursively
Write a function that returns a list of all of the anagrams of a given string. It should use a recursive approach.
def recursiveAnagram(s):
return [] # TODO
For example, if we have mystr = "cat"
, then recursiveAnagrams(mystr)
should return ["cat", "cta", "act", "atc", "tca", "tac"]
.