I’m trying to link two string together recursively, but not getting the expected results:
For the two strings "abcd" and "xyz" – expected output should be "axbyczd":
def strr(str1, str2):
def recstr(str1, str2, prn):
if str1 == '':
return str2
if str2 == '':
return str1
else:
return prn + recstr(str1[:len(str1)-len(prn)],str2[:len(str2)-len(prn)],prn)
return recstr(str1, str2, '')
print strr("abcdef","12345")
When you ran out of characters in either string, you returned the other string without concatenating it to a running accumulator. Look at what I do when
s1ors2is empty.Also, in your recursive case, you have a very complex slicing of
s1ands2. You should really only need to slices1[1:]ands2[1:]This should do it
Of course, a much cleaner way to do this would be to use
itertools.izip_longestanditertools.chain.from_iterable:[Thanks @AshwiniChaudhary for pointing out the
fillvalueparam inizip_longest]Hope this helps