Exercise 37

Write a Python algorithm that creates a list whose elements are the common words to two charcter strings s1 and s2. Give an example.

Solution

def common_words(s1, s2):
    # Convert strings to lists of words
    list1 = s1.split()
    list2 = s2.split()

    # Initialize empty list to store common words
    common_list = []

    # Iterate through words in list1
    for word in list1:
        # Check if word is in list2 and not already in common_list
        if word in list2 and word not in common_list:
            common_list.append(word)

    return common_list

# Example usage
s1 = "Python is an OOP programming"
s2 = "Java is a powerful programming language "
common = common_words(s1, s2)
print(common) # output: ['is', 'programming']




 

Younes Derfoufi
my-courses.net

One thought on “Soultion Exercise 37: list of common words to two strings”

Leave a Reply