My goal is to concatenate two strings using recursion.
The input would be str1 = (“long string”) str2 = (“yes so long”)
and the output would be: ‘lyoensg ssto rlionngg’
Assumptions are that both strings are the same length.
My code as of now is:
def concat_order(str1, str2): if len(str1) == 0: return 'complete' i = 0 new_str = str1[i] + str2[i] i = i + 1 return concat_order(str1[1:], str2[1:]) return new_str print(concat_order("long string"', "yes so long"))
Im sure Im no where close but I am struggling with making it loop.
I am not allowed to use loops but I can use if statements
Advertisement
Answer
def concat_strings_rec(str1, str2): if len(str1) < 1: return "" else: curStr = str1[0] + str2[0] return curStr + concat_strings_rec(str1[1:], str2[1:]) def concat_string_iter(str1, str2): return "".join([str1[i] + str2[i] for i in range(len(str1))]) string1 = "long string" string2 = "yes so long" print(concat_strings_rec(string1, string2)) print(concat_string_iter(string1, string2))
Expected output:
lyoensg ssot rlionngg lyoensg ssot rlionngg
Recursive solution
You need the base case which is when the array length is 0. In that case return an empty string. In all other cases return the first element of each string concatenated with the return value of the recursive call to concat_strings_rec()
. Remember to decrease the array size for the recursive calls!
Iterative solution
The iterative solution just loops through the array concatenating each character within the two strings and putting the concatenated first, second, third,… character in an array. Then use "".join()
to concatenate those two character strings in the array to a complete string.
Recommendation
Don’t use the recursive solution as it just consumes more memory due to the call stack and it will be slower and since Python has a limit on the number of calls on the call stack it will fail for larger strings.