I wrote a python function replace_str that consumes 3 non-empty strings, base, target and rep.
The first string, base represents a base string that you want to update. The second string target represents the target string that you want to replace and the third string rep represents a string that will replace the target in the updated string.
The function produces a new string in which the target string is replaced by the rep string in the base string, but produces the same base string if either of the following conditions hold true.
• If the target string is not found in the base string or,
• If the target and rep are the same strings.
NOT allowed to use the string methods replace and find
This is what I have so far:
def replace_str(base, target, rep):
m = 0
n = len(target)
if base[m:n] == target:
new_base = base[0:m] + rep + base[n:]
return replace_str(new_base, target, rep)
else:
m = m + 1
n = n + 1
return replace_str(base, target, rep)
I'm getting a maximum recursion depth error when I test my program. I'm trying various base cases, as that's where my function gets stuck, but all the base cases I try give me either '' or the last letter of the base
replace_str("aaaax","aa","x")
should produce 'aax'
but gives me an error.
replace_str("aa", "aa", "x")
however gives me the correct result of 'x'
.
Also, this post isn't a duplicate of the other one. The program with the linked post is entirely different and has a different issue. I'm having problems with my base case.