You can only match substrings in all
items because that's exactly what you ask for:
all(testList[0][i:i+j] in x for x in testList)
Even if you change that, you can only find the longest substring that is in the first substring, because you only check through testlist[0]
.
Instead, try something like:
def longest_substr(lst):
longest = None
for word in lst:
for i in range(len(word)):
for j in range(i+1, len(word)+1):
if ((longest is None or (j - i > len(longest))) and
sum(word[i:j] in w for w in lst) > 1):
longest = word[i:j]
return longest
This finds the longest substring that's in at least two (> 1
) of the words (or will return None
for an empty list or list of empty strings) and gives me the following results:
>>> longest_substr(['slide', 'glidb', 'flidt', 'cridz', 'bidr'])
'lid'
>>> longest_substr(['slide', 'glidb', 'flidt', 'cridz', 'bidr', 'balh', 'tejka', 'djakljskdl', 'blah', 'blah', 'blah'])
'blah'
Note that, once you remove the requirement that the substring must be in all strings, the longest in your first list of words is actually 'lid'
.