Exercise 48

Write a Python algorithm as a function which takes as parameters a pair of strings (s1, s2) and which returns the string s obtained by concatenating in an alternative way the characters of s1 and s2. Example: for (s1, s2) = ("Python" , "Java") the function returns the string s = 'PJyatvha'

Solution

def concatenate_alternate(s1, s2):
    s = ''
    for i in range(max(len(s1), len(s2))):
        if i < len(s1):
            s += s1[i]
        if i < len(s2):
            s += s2[i]
    return s
# Example
s1 = "Python"
s2 = "Java"
s = concatenate_alternate(s1, s2)
print(s)  # Output: PJyatvha





In this algorithm:

  1. we create an empty string s: which will hold our concatenated string.
  2. We use the max() function: to get the length of the longer string so we know how many iterations we need to do.
  3. We loop through each index i: up to the length of the longer string.
  4. For each iteration: we check if i is within the bounds of s1 and s2. If it is, we add the character at index i from the respective string to our s string.
  5. Finally: we return the concatenated s string.

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 48: python program that concatenate two string in alternative way”

Leave a Reply