Exercise 61

Write a Python algorithm as function which takes a string 's' as input and return an other string obtained by removing the duplicate characters of 's'. Example: if s = "Programming", the function must retun "Progamin"

Solution

You can implement this by iterating over the characters of the string and keeping track of the characters you've seen so far using a set. If you encounter a character that's not in the set, you add it to the output string and the set. Otherwise, you skip it. Here's the Python function that implements this:

def remove_duplicates(s):
    seen = set()
    output = ''
    for char in s:
        if char not in seen:
            output += char
            seen.add(char)
    return output

# To use this function, you can simply call it with a string argument:
s = "Programming"
result = remove_duplicates(s)
print(result) # Outputs "Progamin"




 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 61: Python program which remove the duplicate characters from given string”

Leave a Reply