Question
How should one go about writing a recursive function? Have the function call itself, and use a try...except clause to terminate the function when a
How should one go about writing a recursive function?
Have the function call itself, and use a try...except clause to terminate the function when a memory error occurs.
Write the function using a for loop first, then try to replace each iteration with a recursive call.
Just insert a call to the function inside its definition and see what happens.
Figure out how to break the problem down into smaller problems of the same type, so that the base case is eventually reached.
Given this definition:
def reverse_str(st, pos=0, rev=\"\"):
Returns a new string that is the reverse of st When first called, the pos parameter must be zero and the rev parameter must be \"\" (the empty string)---
if pos == len(st):
return rev
return reverse_str(st, pos+1, st[pos] + rev)
If you were to call the function like so:
reverse_str(\"bananas\")
What would be the value of \"rev\" when the base case is reached?
'bananas
7
Os
'sananab
Have the function call itself, and use a try...except clause to terminate the function when a memory error occurs.
Write the function using a for loop first, then try to replace each iteration with a recursive call.
Just insert a call to the function inside its definition and see what happens.
Figure out how to break the problem down into smaller problems of the same type, so that the base case is eventually reached.
Given this definition:
def reverse_str(st, pos=0, rev=\"\"):
Returns a new string that is the reverse of st When first called, the pos parameter must be zero and the rev parameter must be \"\" (the empty string)---
if pos == len(st):
return rev
return reverse_str(st, pos+1, st[pos] + rev)
If you were to call the function like so:
reverse_str(\"bananas\")
What would be the value of \"rev\" when the base case is reached?
'bananas
7
Os
'sananab
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started