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