Exercise 89

Write a Python script that takes a string s as input and which returns the list of repeated charcters in the string s. Example: if s = "Programming language", the algorithm returns the list:

01
['r', 'g', 'a', 'm', 'n']

Solution

We can solve this by iterating through the string and keeping track of characters that are repeated.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
def find_repeated_chars(s):
    repeated_chars = []
    seen_chars = set()
 
    for char in s:
        if char in seen_chars and char not in repeated_chars:
            repeated_chars.append(char)
        else:
            seen_chars.add(char)
 
    return repeated_chars
 
# Example usage:
s = "Programming language"
print(find_repeated_chars(s))
# output : ['r', 'm', 'g', 'a', 'n']

 

Younes Derfoufi
www.my-courses.net

One thought on “Solution Exercise 89 : repeated charcters in given a python string”

Leave a Reply