Write a Python function to remove repeated consecutive characters and replace them with single letters and return the updated string.
Example:
Input: (“Red Green White”) -> Output: “Red Gren White”
Input: (“aabbbcdeffff”) -> Output: “abcdef”
Solution
Try the exercise on your own first, then compare with the worked solution below.
# Solution 1def remove_duplicates(s):""" Removes repeated consecutive characters in a string """ result =""for char in s:ifnot result or char != result[-1]: result += charreturn result# Test the function with the provided examplestest1 ="Red Green White"result1 = remove_duplicates(test1)print(result1)test2 ="aabbbcdeffff"result2 = remove_duplicates(test2)print(result2)
Red Gren White
abcdef
# Solution 2def remove_duplicates(s):""" Removes repeated consecutive characters in a string """ empty_ls = []for i inrange(0, len(s)-1):if s[i] != s[i+1]: empty_ls.append(s[i])return"".join(empty_ls) + s[-1]# Test the function with the provided examplestest1 ="Red Green White"result1 = remove_duplicates(test1)print(result1)test2 ="aabbbcdeffff"result2 = remove_duplicates(test2)print(result2)
Red Gren White
abcdef
Source Code
---title: "Review: Remove Duplicates"subtitle: "Module 4: IDEs & Tools"format: html---## Remove DuplicatesWrite a Python function to remove repeated consecutive characters and replace them with single letters and return the updated string.Example:- Input: ("Red Green White") -> Output: "Red Gren White"- Input: ("aabbbcdeffff") -> Output: "abcdef"::: {.callout-tip collapse="true"}## SolutionTry the exercise on your own first, then compare with the worked solution below.```{python}# Solution 1def remove_duplicates(s):""" Removes repeated consecutive characters in a string """ result =""for char in s:ifnot result or char != result[-1]: result += charreturn result# Test the function with the provided examplestest1 ="Red Green White"result1 = remove_duplicates(test1)print(result1)test2 ="aabbbcdeffff"result2 = remove_duplicates(test2)print(result2)``````{python}# Solution 2def remove_duplicates(s):""" Removes repeated consecutive characters in a string """ empty_ls = []for i inrange(0, len(s)-1):if s[i] != s[i+1]: empty_ls.append(s[i])return"".join(empty_ls) + s[-1]# Test the function with the provided examplestest1 ="Red Green White"result1 = remove_duplicates(test1)print(result1)test2 ="aabbbcdeffff"result2 = remove_duplicates(test2)print(result2)```:::