Exercise 87

Write a Python script which takes as input a tuple of two strings (s1, s2) and which returns the list of common characters to s1 and s2.
Example: if s1 = 'Python language' and s2 = 'Java Programming', the function returns:

['P', 'o', 'n', ' ', 'a', 'g']

Solution

"""
We can achieve this by converting both strings to sets 
of characters and then finding the intersection of the sets
"""
def common_characters(s1, s2):
    # Convert both strings to sets of characters
    set1 = set(s1)
    set2 = set(s2)
    
    # Find the intersection of the sets
    common_chars = set1.intersection(set2)
    
    # Convert the set of common characters back to a list and return
    return list(common_chars)

# Example usage:
s1 = 'Python language'
s2 = 'Java Programming'
result = common_characters(s1, s2)
print(result)  # Output: ['P', 'o', 'n', ' ', 'a', 'g']

 

Younes Derfoufi
www.my-courses.net

One thought on “Solution Exercise 87 : Finding the set of common characters of two strings”

Leave a Reply