### Thread: Adding of the two strings with help of Python in recursive manner

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
3
Rep Power
0

#### Adding of the two strings with help of Python in recursive manner

Hello Friends,
Here I write a piece of code for adding two strings. For e.g. if first string is "xyz" and second is "pqrstu" then the final out should be "xpyqzrstu"... But the condition is to use only if and else condition.. We cant use any loop mechanism or any thing else..

def helpLaceStrings(s1, s2, out):
if s1 == '':
a single line code here
if s2 == '':
a single line code here
else:
a single line code here
return helpLaceStrings(s1, s2, '')
2. Originally Posted by nishakothari1
Hello Friends,
Here I write a piece of code for adding two strings. For e.g. if first string is "xyz" and second is "pqrstu" then the final out should be "xpyqzrstu"... But the condition is to use only if and else condition.. We cant use any loop mechanism or any thing else..

def helpLaceStrings(s1, s2, out):
if s1 == '':
a single line code here
if s2 == '':
a single line code here
else:
a single line code here
return helpLaceStrings(s1, s2, '')
Why do you need recursion? What are you doing over and over and what condition are you doing it until? That is, why won't:
Code:
```def helpLaceStrings(s1, s2, out):
if s1 == '':
out = s2
if s2 == '':
out = s1
else:
out = s1+s2```
work?
3. Rrashkin: if you look again at the problem statement, the goal is to interlace the two strings, not just concatenate them.
4. Originally Posted by Schol-R-LEA
Rrashkin: if you look again at the problem statement, the goal is to interlace the two strings, not just concatenate them.
Code:
```s1="xyz"
s2="pqrstu"
out=""
def lace(s1,s2,out):
len1=len(s1)
len2=len(s2)
if len1>len2:
s2=s2+(len1-len2)*' '
else: s1=s1+(len2-len1)*' '
out=out+s1[0]+s2[0]
s1=s1[1:]
s2=s2[1:]
if len(s1)>0: out=lace(s1,s2,out).replace(' ','')
return out
out=lace(s1,s2,out)
print out```
5. No Profile Picture
Permanently Banned
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2012
Posts
7
Rep Power
0

#### Re: Add two string with python in recrusive

def str_cat(str1, str2, index = 0, out = ''):

if index < len(str1):
try: #if len(str1) than str2
out = out + str1[index] + str2[index]
index = index + 1
return str_cat(str1, str2, index, out)
except:
out = out + str1[index:]
return out
else: #if len(str2) than str1
if index <= len(str2):
return out+str2[index:]

s1= 'abc'
s2 = 'xyz456'
res = str_cat(s1,s2)
print res