Python | Ways to determine common prefix in set of strings
Given a set of strings, write a Python program to determine common prefix from a set of strings. Given below are a few methods to solve the above task.
Method #1: Using Naive Approach
Python3
ini_strlist = [ 'akshat' , 'akash' , 'akshay' , 'akshita' ]
res = ''
prefix = ini_strlist[ 0 ]
for string in ini_strlist[ 1 :]:
while string[: len (prefix)] ! = prefix and prefix:
prefix = prefix[: len (prefix) - 1 ]
if not prefix:
break
res = prefix
print ( "Resultant prefix" , str (res))
|
Output:
Resultant prefix ak
Method #2: Using itertools.takewhile and zip
Python3
from itertools import takewhile
ini_strlist = [ 'akshat' , 'akash' , 'akshay' , 'akshita' ]
res = ''.join(c[ 0 ] for c in takewhile( lambda x:
all (x[ 0 ] = = y for y in x), zip ( * ini_strlist)))
print ( "Resultant prefix" , str (res))
|
Output:
Resultant prefix ak
Complexity Analysis:
In both the solutions time and space complexity are the same:
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method #3: Using the Python built-in function os.path.commonprefix()
This method uses the os.path.commonprefix() built-in function in the python os library to find the common prefix of a set of strings.
Python3
import os
ini_strlist = [ 'akshat' , 'akash' , 'akshay' , 'akshita' ]
prefix = os.path.commonprefix(ini_strlist)
print ( "Resultant prefix" , prefix)
|
Output
Resultant prefix ak
Time Complexity: O(n*l) where n is the number of strings in the set and l is the length of the longest string.
Auxiliary Space: O(n)
The above code import the os library and then use the os.path.commonprefix(ini_strlist) function on the set of strings. The function return the common prefix among all the string in set.
Last Updated :
11 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...