Assume I have the string "my name is", how do I recursively return the string "mmyy nnaammee iiss"?
CodePudding user response:
you could do something like
def double(s):
out = ''
for letter in s:
out=out s s
return out
this has
INPUT:print(double("hello"))
OUTPUT:hheelllloo
CodePudding user response:
The following is simple enough. Double the first letter, and recursively call for the rest. Base case: empty string:
def double(s):
if not s:
return s
return 2 * s[0] double(s[1:])
double("my name is")
# 'mmyy nnaammee iiss'
Note that the repeated slicing of the recursive approach and the repeated string concatenation of the other answer make both solutions quadratic in time complexity. Algorithmically sounder (linear) would be str.join
ing a linearly built list or a generator expression:
def double(s):
return "".join(2*c for c in s)