Exercise 91 ***
Write a python algorithm which determines the common words with maximum length of two strings text T1 and T2. Example if: T1 = "Python created by Guidorossum is open source programming language. Python was created on 1991"and T2 = "Python created by Guidorossum is the most popular programming language Guidorossum", the algorithm returns the list:
['Guidorossum', 'programming']
Solution
#creating a method which determines the list of common words in T1 and T2
def commonWords(T1 , T2):
# converting the texts into lists
listWords_in_T1 = T1.split()
listWords_in_T2 = T2.split()
# initializing the common words
listCommon_words = []
for word in listWords_in_T1 :
if word in listWords_in_T2 and word not in listCommon_words:
listCommon_words.append(word)
return listCommon_words
# Creating a methode that determines the common word with maximum length
def commonMax(T1, T2):
listCommon_words = commonWords(T1 , T2)
# initializing the maximum length
maxLength = 0
for word in listCommon_words:
if len(word) >= maxLength:
maxLength = len(word)
# searching the the common words of maximum length
listCommonWordMax = []
for word in listCommon_words:
if len(word) == maxLength:
listCommonWordMax.append(word)
return listCommonWordMax
T1 = "Python created by Guidorossum is open source programming language. Python was created on 1991"
T2 = "Python created by Guidorossum is the most popular programming language Guidorossum"
print(commonMax(T1 , T2))
# The output is: ['Guidorossum', 'programming']
Younes Derfoufi
my-courses.net
my-courses.net