Exercises
Exercise 1
Draw a stack diagram for the following program. What does the program print?
def b(z):
prod = a(z, z)
print(z, prod)
return prod
def a(x, y):
x = x + 1
return x * y
def c(x, y, z):
sum = x + y + z
pow = b(sum)**2
return pow
x = 1
y = x + 1
print c(x, y+3, x+y)Exercise 2
The Ackermann function, , is defined by:
Write a recursive function named ackerman that evaluates Ackerman's function. Use your function to evaluate ackerman(3, 4), which should be 125. What happens for larger values of m and n?
Exercise 3
A palindrome is a word that is spelled the same backward and forward, like noon and redivider. Recursively, a word is a palindrome if the first and last letters are the same and the middle is a palindrome. The following are functions that take a string argument and return the first, last, and middle letters:
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]Type these functions into a file named
.pyand test them out. What happens if you callmiddlewith a string with two letters? One letter? What about the empty string, which is written''and contains no letters?Write a recursive function called
is_palindromethat takes a string argument and returnsTrueif it is a palindrome andFalseotherwise. Remember that you can use the built-in functionlento check the length of a string.
Exercise 4
A number, , is a power of if it is divisible by and is a power of . Write a recursive function called is_power that takes parameters a and b and returns True if a is a power of b, False otherwise.
Exercise 5
This exercise is based on an example from Abelson and Sussman's "Structure and Interpretation of Computer Programs". The greatest common divisor (GCD) of and is the largest number that divides both of them with no remainder. One way to find the GCD of two numbers is Euclid's algorithm, which is based on the observation that if is the remainder when is divided by , then . As a base case, we can consider .
Write a recursive function called gcd that takes parameters a and b and returns their greatest common divisor.
Last updated