Change language

Python | Ways to Determine a Common Prefix in a Stringset

|

Method # 1: Taking a Naive Approach

# Python code for demo
# find common prefix
# from rowset

 
# Initializing string

ini_strlist = [ ’akshat’ , ’akash’ , ’ akshay’ , ’akshita’ ]

  
# Find the commom prefix using a 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

 
# Print result

print ( "Resultant prefix" , str (res))

Exit:

 Resultant prefix ak 

Method # 2: Using itertools.takewhile and zip

# Python code for demo
# find common prefix
# from set lines

 

from itertools import takewhile

  
# Initializing string

ini_strlist = [ ’akshat’ , ’akash’ , ’ akshay’ , ’akshita’ ]

  
# Find the commom prefix using a naive approach

res = ’ ’.join (c [ 0 ] for c in takewhile ( lambda x:

all (x [ 0 ] = = y for y in x), zip ( * ini_strlist)))

 
# Print result

print ( "Resultant prefix" , str (res))

Output:

 Resultant prefix ak 

Python | Ways to Determine a Common Prefix in a Stringset Python functions: Questions

Python | Ways to Determine a Common Prefix in a Stringset String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method