Reputation: 11
So I was creating a simple recursive function which essentially compares two strings, 'string' and 'target', and if they're the same, the function replaces the 'target' with 'rep', much like the function of find and replace you would see in a text editor. My issue is, is that the function returns nothing. Is that because it hasn't hit my base case or am I missing an extra return somewhere?
def helperfn(string,target,rep,x): # x is always initially set to zero
if x==len(string): #base case
target=rep
return target
if len(string)==len(target):
if string[x]==target[x]:
helperfn(string,target,rep,(x+1))
else:
return "string and target are not the same"
A few examples of what the expected output should be:
helperfn("noway","noway","yes",0)=>"yes"
helperfn("ok","ok","never",0)=>"never"
Upvotes: 0
Views: 35
Reputation: 31
When you call the function recursively, you want to return that value.
return helperfn(string,target,rep,(x+1))
Upvotes: 3
Reputation: 122383
It's because you never returned anything explicitly in one branch. Change
if len(string)==len(target):
if string[x]==target[x]:
helperfn(string,target,rep,(x+1))
to
if len(string)==len(target):
if string[x]==target[x]:
return helperfn(string,target,rep,(x+1))
Upvotes: 1