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. >>> weave('aaaaaa', 'bbbbbb') result: 'abababababab' >>> weave('abcde', 'VWXYZ') result: 'aVbWcXdYeZ' >>> weave('aaaaaa', 'bb') # four extra 'a' characters at the end result: 'ababaaaa' >>> weave('aaaa', 'bbbbbb') # two extra 'b' characters at the end result: 'ababababbb' >>> weave('aaaa', '') # all of the 'a' characters are extra! result: 'aaaa' >>> weave('', 'bbbb') # all of the 'b' characters are extra! result: 'bbbb' >>> weave('', '') result: '' Hint: You will need more than one base case
can someone please explain it step by step .
def weave(s1, s2): if len(s1) > 0 and len(s2) > 0: # if both s1 and s2 are non-empty # then weave a letter from s1 and a letter from s2 and recursively weave rest of letters from s1 and s2 return s1[0] + s2[0] + weave(s1[1:], s2[1:]) elif len(s1) > 0: # if only s1 is not empty return s1 # then return s1 else: # if only s2 is not empty return s2 # then return s2 print(weave('aaaaaa', 'bbbbbb')) print(weave('abcde', 'VWXYZ')) print(weave('aaaaaa', 'bb')) print(weave('aaaa', 'bbbbbb')) print(weave('aaaa', '')) print(weave('', 'bbbb')) print(weave('', ''))
Get Answers For Free
Most questions answered within 1 hours.