- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to merge strings alternately using Python
Suppose we have two strings s and t. We have to merge them by adding letters in alternating fashion, starting from s. If s and t are not of same length, add the extra letters onto the end of the merged string.
So, if the input is like s = "major" t = "general", then the output will be "mgaejnoerral", as t is larger than s, so we have added extra part "ral" at the end.
To solve this, we will follow these steps −
i := j := 0
result := blank string
while i < size of s and j < size of t, do
result := result concatenate s[i] concatenate t[j]
i := i + 1
j := j + 1
while i < size of s, do
result := result concatenate s[i]
i := i + 1
while j < size of t , do
result := result concatenate t[j]
j := j + 1
return result
Let us see the following implementation to get better understanding −
Example
def solve(s, t): i = j = 0 result = "" while i < len(s) and j < len(t): result += s[i] + t[j] i+=1 j+=1 while i < len(s): result += s[i] i += 1 while j < len(t): result += t[j] j += 1 return result s = "major" t = "general" print(solve(s, t))
Input
"major", "general"
Output
mgaejnoerral