Write a Python program to find the longest common prefix from a list of strings.
1 Like
'''
In this program i am trying to find common part between first two values and
comparing it to the next values one by one.
'''
def find_suffix(str1,str2):
# this function compares two strings
# determine smallest length to work with as the
# maximum possible suffix should be smallest string from the input
end = len(str1) if(len(str1) <= len(str2)) else len(str2)
suf=''
for i in range(0,end):
# compare character at each position from two strings
if str1[i]==str2[i]:
# if same character is there, add it to the suffix
suf = suf + str1[i]
else:
# if different character is present for two strings at same position
#stop checking furthur
break
return suf
def main():
x = input('Enter string values(comma separated): ')
# l is list to store the input values
l = x.split(',')
# l = ['him', 'his', 'hit', 'hip']
# if no input is there print no input
if len(l) == 0:
print('no input')
# if only one input is there print that as suffix
elif len(l) == 1:
print('suffix is: ',l[0])
# if more than one inputs are there
else:
#comapre first two strings to find common part
suf = find_suffix(l[0],l[1])
# after getting first suffix compare it with other
# input strings if suffix is present or not
for i in range(2,len(l)):
suf = find_suffix(suf,l[i])
if suf:
print('suffix is ',suf)
else:
print('no suffix found')
main()
'''
input: 'arm','armenia','argentina'
1. compare 'arm' and 'armenia'
suffix: 'arm'
2. compare 'arm' and 'argentina'
suffix: 'ar'
'''
1 Like