Python | Merge two strings with suffix and prefix

Python Methods and Functions | String Variables

You are given two lines A and B, and these lines contain lowercase letters. The challenge is to specify the length of the merged strings. For example, if A — "Abcde", and B — "Cdefg" then concatenation of the two strings results in "abcdefg". The merge operation is performed such that the characters to be appended are suffix A and prefix B.
Before merging, you are allowed to perform ONE of the following operations:

  1. Backward Line A
  2. Backward Line B

Examples :

  Input:  A = "ababc" B = "bcabc"  Output:  Length is 8 the suffix of string A ie "bc" and prefix of B ie "bc" is the same so the merged string will be "ababcabc" and length is 8.  Input:  A = "cdefg" B = "abhgf"  Output:  Length is 8 the suffix of string A ie "fg" and prefix of reversed B ie "fg" is the same so the merged string will be "cdefghba" and length is 8  Input:  A = "wxyz" B = "zyxw"  Output:  Length is 4 

Below is the Python code implementation of the above approach.

# function to find length
# concatenated string

 

def mergedstring (x, y) :

 

k = len (y)

for i in range ( len (x)):

 

if x [i:] = = y [: k]:

break

else :

k = k - 1

  

# uncomment the following statement

# know what a concatenated string is

# print (a + b [k:])

return len (a + b [k:])

  
# function to find the minimum length
# among the concatenated string

def merger (a, b):

# reverse b

b1 = b [:: - 1

 

# function call to determine length

# lines without backlines & # 39; B & # 39;

r1 = mergedstring (a, b)

  

# function call to determine length

# lines by reversing line "B"

r2 = mergedstring (a, b1)

 

# compare between lengths

if r1 & gt; r2:

print ( "Length is" , r2)

else :

print ( "Length is" , r1)

 
# driver code

a = "abcbc"

b = "bcabc"

 
merger (a, b)

Exit :

 Length is 8 




Get Solution for free from DataCamp guru