Discussion 5: Recursion
Recursion
Recursion is when a function calls itself to solve a smaller version of the same problem. Instead of tackling a complex task all at once, recursion breaks it down into simpler steps until it reaches a base case.
Many students find this topic challenging. Everything gets easier with practice. Please help each other learn.
Q1: Swipe
Implement swipe
, which prints the digits of argument n
, one per line, first backward then forward. The left-most digit is printed only once. Do not use while
or for
or str
. (Use recursion, of course!)
print
the first line of the output, then make a recursive call, then print
the last line of the output.
Q2: Skip Factorial
Define the base case for the skip_factorial
function, which returns the product of every other positive integer, starting with n
.
n
is even, then the base case will be 2. If n
is odd, then the base case will be 1. Try to write a condition that handles both possibilities.
Q3: Recursive Hailstone
Recall the hailstone
function from Homework 2.
First, pick a positive integer n
as the start. If n
is even, divide it by 2.
If n
is odd, multiply it by 3 and add 1. Repeat this process until n
is 1.
Complete this recursive version of hailstone
that prints out the values of the
sequence and returns the number of steps.
even
always makes a recursive call to hailstone
and returns one more than the length of the rest of the hailstone sequence.
An odd number might be 1 (the base case) or greater than one (the recursive case). Only the recursive case should call hailstone
.
Extra Questions
The questions below are optional but recommended if you would like some extra practice.
Q4: Is Prime
Implement is_prime
that takes an integer n
greater than 1. It returns True
if n
is a prime number and False
otherwise. Try following the approach
below, but implement it recursively without using a while
(or for
)
statement.
You will need to define another "helper" function (a function that exists just
to help implement this one). Does it matter whether you define it within
is_prime
or as a separate function in the global frame? Try to define it to
take as few arguments as possible.
i
and n
evenly divides n
. Then you can call it starting with i=2
:
def is_prime(n):
def f(i):
if i == n:
return ____
elif ____:
return ____
else:
return f(____)
return f(2)
Q5: Function Repeater
Define a function make_fn_repeater
which takes in a one-argument function f
and an integer x
.
It should return another function which takes in one argument, another integer.
This function returns the result of applying f
to x
this number of times.
Make sure to use recursion in your solution.
Run in 61A Code