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
# Python code to demonstrate# to find common prefix# from set of strings# Initialising stringini_strlist = ['akshat', 'akash', 'akshay', 'akshita']# Finding common prefix using Naive Approachres = ''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: breakres = prefix# Printing resultprint("Resultant prefix", str(res)) |
Output:
Resultant prefix ak
Method #2: Using itertools.takewhile and zip
Python3
# Python code to demonstrate# to find common prefix# from set of stringsfrom itertools import takewhile# Initialising stringini_strlist = ['akshat', 'akash', 'akshay', 'akshita']# Finding common prefix using Naive Approachres = ''.join(c[0] for c in takewhile(lambda x: all(x[0] == y for y in x), zip(*ini_strlist)))# Printing resultprint("Resultant prefix", str(res)) |
Output:
Resultant prefix ak
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


