# Solution Exercise 68: python algorithm to compute the numer of shared characters in two strings

Apr 18, 2023

#### Exercise 68

Write a python program as function which takes a tuple of string (s1 , s2) and return the number of common characters in s1 and s2. Example: if s = “Hello” and s2 = “World”, the shared characters are ‘l’ and ‘o’, then the algorithm returns 2.

#### Solution

```"""
We can solve this problem by iterating through each character
of one string and checking if it exists in the other string.
"""
def count_common_chars(s1, s2):
# we initialize a count variable to 0
count = 0

"""iterates through each character in s1. For each character,
it checks if it exists in s2 using the in operator.
If the character is found in s2, it increments the count variable"""
for char in s1:
if char in s2:
count += 1
s2 = s2.replace(char, '', 1) # remove the matched char from s2 to avoid counting it twice
return count
s1 = "Hello"
s2 = "World"
common_count = count_common_chars(s1, s2)
print(common_count) # Output: 2```

Younes Derfoufi
CRMEF OUJDA