1. Write a function double (s) that takes an arbitrary string s as input, and th
ID: 3872899 • Letter: 1
Question
1. Write a function double (s) that takes an arbitrary string s as input, and that uses recursion to construct and return the string formed by doubling each character in the string. Here are three examples: >double('hello') >doubleC'python) ppyytthhoonn' >>>double(") 2. 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) abababababab >>>weave('abcde' 'VWXYZ avbwcxdYez >>> weave('aaaaaa', 'bb') # four extra 'a' characters at the end ababaaaa" >>> weave ('aaaa', 'bbbbbb') # two extra 'b' characters at the end ababababbb >>>weave('aaaa', '") # all of the 'a' characters are extra! >weave(', "bbbb) # all of the 'b' characters are extra! weave(', '")Explanation / Answer
1)
def double(s):
if not s:
return s
head, tail = s[0:1], s[1:]
return (head * 2) + double(tail)
2)
def weave(a,b):
if a == "":
return b
if b == "":
return a
return a[0] + b[0] + weave(a[1:], b[1:])
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.