64.7k views
0 votes
Define a recursive function named merge chars, it is passed two str arguments, in which all the characters appear in alphabetic order; it returns a str that contains all the characters in its argument strings, also appearing in alphabetic order.

User Diwatu
by
5.3k points

1 Answer

3 votes

Answer:

def merge_chars(str1, str2):

if not str1 and not str2:

return ''

if str1 and (not str2 or str1[0] <= str2[0]):

return str1[0] + merge_chars(str1[1:], str2)

else:

return str2[0] + merge_chars(str1, str2[1:])

Note: It's written in Python3

Step-by-step explanation:

This line defines the function

def merge_chars(str1, str2):

This checks for empty strings. If yes, it return an empty string

if not str1 and not str2:

return ''

The following merge and sorts both strings, recursively

This checks if only one of the strings is not empty

if str1 and (not str2 or str1[0] <= str2[0]):

return str1[0] + merge_chars(str1[1:], str2)

This checks if both strings are not empty

else:

return str2[0] + merge_chars(str1, str2[1:])

User Hknust
by
4.9k points