Skip to content

Instantly share code, notes, and snippets.

@pravj
Created April 15, 2020 14:08
Show Gist options
  • Save pravj/a29d2a2bf503bcb2e681fc49361377bf to your computer and use it in GitHub Desktop.
Save pravj/a29d2a2bf503bcb2e681fc49361377bf to your computer and use it in GitHub Desktop.
# Python 3 program to find the stem
# of given list of words
# function to find the stem (longest
# common substring) from the string array
def findstem(arr):
# Determine size of the array
n = len(arr)
# Take first word from array
# as reference
s = arr[0]
l = len(s)
res = ""
for i in range( l) :
for j in range( i + 1, l + 1) :
# generating all possible substrings
# of our reference string arr[0] i.e s
stem = s[i:j]
k = 1
for k in range(1, n):
# Check if the generated stem is
# common to all words
if stem not in arr[k]:
break
# If current substring is present in
# all strings and its length is greater
# than current result
if (k + 1 == n and len(res) < len(stem)):
res = stem
return res
# Driver Code
if __name__ == "__main__":
# arr = [ "jay6569838", "j6569838", "je6569838" ]
arr = [ "jay", "j", "je" ]
stems = findstem(arr)
print(stems)
# This code is contributed by ita_c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment