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:

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

Solution

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

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