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
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
Get step-by-step solutions from verified subject matter experts
