Learn data science and machine learning by building real-world projects on Jovian

finding-common-prefix-in-list-of-strings

Use the "Run" button to execute the code.

In [ ]:
!pip install jovian --upgrade --quiet
In [ ]:
import jovian
In [3]:
# Execute this to save new versions of the notebook
jovian.commit(project="finding-common-prefix-in-list-of-strings")
[jovian] Updating notebook "sushanth2903/finding-common-prefix-in-list-of-strings" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/sushanth2903/finding-common-prefix-in-list-of-strings
Inputs for your references:

["absence", "absolute", "abroad","abstract","apple"]
["absence", "absolute", "abstract"]
["absence", "absolute", "abroad","abstract","test"]
["absence", "absolute", "abroad","abstract"]
In [22]:
import ast
str_multi= ast.literal_eval(input())

# finding lenght of shortest string
min_str= len(str_multi[0])
for i in range(1,len(str_multi)):
    if len(str_multi[i])<min_str:
        min_str=len(str_multi[i])
min_str


prefix=str_multi[0] #temporary assignement of 1st string as prefix

p= int(min_str)
for i in range(p):
    for j in str_multi:
        if prefix[:p] in j[:p]:
            pass
        else:
            p-=1 #reducing the slicing value of string by one if the entire slice of 'prefix' doesn't match

if p==0:
    print ("There is no common prefix for every string in the list")
else:
    print (f'The common prefix for every string in the list is "{prefix[0:p]}"')
["absence", "absolute", "abroad","abstract"] The common prefix for every string in the list is "ab"
In [ ]: