Exercise 75

Create a Python algorithm that identifies the list of unique common characters between two strings, s1 and s2, without any repetitions.
For example : if s1 = "Python language" and s2 = "Programming" the algorithm should generate a list like ['P', 'o', 'n', 'a', 'g'] (ensuring that the character 'g' is included only once, even if it appears more than once in either string).

Solution

def common_characters(s1, s2):
    # Convert strings to sets of unique characters
    set_s1 = set(s1)
    set_s2 = set(s2)

    # Find the intersection of the two sets
    common_chars_set = set_s1.intersection(set_s2)

    # Convert the set to a sorted list
    common_chars_list = sorted(list(common_chars_set))

    return common_chars_list

# Example usage
s1 = "Python language"
s2 = "Programming"

result = common_characters(s1, s2)
print(result) # output: ['P', 'a', 'g', 'n', 'o']




 

Younes Derfoufi
CRMEF OUJDA

One thought on “Solution Exercise 75 : Finding Unique Common Characters in Two Strings”

Leave a Reply