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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# to find common prefix
# from set of strings
  
# Initialising string
ini_strlist = ['akshat', 'akash', 'akshay', 'akshita']
  
# Finding commom prefix using Naive Approach
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
  
# Printing result
print("Resultant prefix", str(res))

chevron_right


Output:

Resultant prefix ak

 
Method #2: Using itertools.takewhile and zip

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# to find common prefix
# from set of strings
  
from itertools import takewhile
  
# Initialising string
ini_strlist = ['akshat', 'akash', 'akshay', 'akshita']
  
# Finding commom prefix using Naive Approach
res = ''.join(c[0] for c in takewhile(lambda x:
        all(x[0] == y for y in x), zip(*ini_strlist)))
  
# Printing result
print("Resultant prefix", str(res))

chevron_right


Output:

Resultant prefix ak


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.