Exercise 84

Create a Python function that accepts a string 's' as a parameter and produces a list containing all the characters that appear more than once in the given string.
For instance:

When the input string is s = "python language" the function should output the list ['n', 'a', 'g'].

Solution

def find_repeated_characters(s):
    # Create an empty list to store repeated characters
    repeated_characters = []

    # Create a set to keep track of characters that have been seen
    seen_characters = set()

    # Iterate through each character in the string
    for char in s:
        # Check if the character is already in the set (indicating repetition)
        if char in seen_characters and char not in repeated_characters:
            repeated_characters.append(char)
        else:
            seen_characters.add(char)

    return repeated_characters

# Example usage
s = "python language"
result = find_repeated_characters(s)
print(result) # output : ['n', 'a', 'g']



 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 84 : Python Function for Finding Repeated Characters in a String”

Leave a Reply