Given two string write a function to merge both by taking characters alternatively
s1 = "Python"
s2 = "Django"
Output = "PDyjtahnogno"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def mergeAlternative(s1, s2): | |
result = "" # output | |
# using while loop to get each character | |
i = 0 # index for while | |
while i < len(s1): | |
result += s1[i] + s2[i] | |
i += 1 | |
# end while | |
return result | |
s1 = "Python" | |
s2 = "Django" | |
print(mergeAlternative(s1, s2)) |
Observe it carefully program will work when the length of both strings are equal. However, it fails when two strings are of different length and gives an error.
ERROR: index out of range.
A solution to handle this situation.
s1 = "Javascript"
s2 = "NodeJS"
Output = "JNaovdaeSJcSript"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def mergeAlternative(s1, s2): | |
result = "" | |
i, j = 0, 0 | |
while i < len(s1) or j < len(s2): # will work for both index | |
if i < len(s1): # check if exists then print | |
result += s1[i] | |
i += 1 | |
if j < len(s2): | |
result += s2[j] | |
j += 1 | |
# end while | |
return result | |
s1 = "JavaScript" | |
s2 = "NodeJS" | |
print(mergeAlternative(s1, s2)) | |
# you can also take iterate using single comparison which is bigger |
Merge two strings by taking characters alternatively
Reviewed by Leaf Code
on
August 09, 2020
Rating:

No comments: