Write a function weave(s1, s2) that takes as inputs two strings s1 and s2 and uses recursion to construct and return a new string that is formed by "weaving" together the characters in the strings s1 and s2 to create a single string. In other words, the new string should alternate characters from the two strings: the first character from s1, followed by the first character from s2, followed by the second character from s1, followed by the second character from s2, etc. If one of the strings is longer than the other, its "extra" characters – the ones with no counterparts in the shorter string – should appear immediately after the "woven" characters (if any) in the new string.

Respuesta :

Answer:

#program in Python.

#function

def weave(s1,s2):

   #if both are empty string

   if(len(s1)==0 and len(s2)==0):

       #return an empty string

       return ""

   #if length of both is greater than 0

   elif(len(s1)>0 and len(s2)>0):

       # recursive call to weave both strings

       return s1[0]+s2[0]+weave(s1[1:],s2[1:])

   # if character in s1 is left

   elif(len(s1)>0):

       #append them to new string

       return s1[0]+weave(s1[1:],s2)

   # if character in s2 is left

   else:

       ##append them to new string

       return s2[0] + weave(s1, s2[1:])

#read frist string

s1=input("Enter first string:")

#read second string

s2=input("Enter second string:")

#call the function

s3=weave(s1, s2)

#print new string

print("New string is:",s3)

Explanation:

Read two string from user and assign them to variables "s1" & "s2".Call the  function weave()with both the strings as parameter.This function will recursively weave the characters of both the strings.If character left in any of the string then  it will be added to the last of the woven string.

Output:

Enter first string:aaaa                                                                                                    

Enter second string:bbbbbbb                                                                                                

New string is: ababababbbb