Answer to Question #285294 in Python for Munif

Question #285294

Given a string, create a new string with all the consecutive duplicates removed.

=====================================================================

Hint: You may make a new string to store the result. You can check whether the current character and the next character are the same, then add that character to the new string.


1
Expert's answer
2022-01-07T01:49:39-0500
# enter given string
str1 = input()
# add symbol that will not exist in the string,
# to process the last symbol correctly
str1 += "@" 
# another string to store the result
str2 = ""
# run until last character in initial string
for i in range(len(str1) - 1):
  # check whether the current character and the next character are the same
  if str1[i] != str1[i + 1]:
    # if not the same, add character to the new string
    str2 += str1[i]
print(str2)

If the input is "abcde", the string will be "abcde@", and the last comparison will be 'e' vs '@', (which is not the same for any input), and that last symbol will be added in any case.

If the input is "abcdeee", then all previous 'e' will be ignored (they are the same), and th last one will be appended, as it is different from "@"


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS