0

So, I've seen a lot of answers for removing duplicate characters in strings, but I'm not trying to remove all duplicates - just the ones that are beside each other.

This is probably a lot more simple than what I'm doing, but this is what I've been attempting to do (and failing miserably at)

for j in range(2, len(string)-1):
  char = string[j]
  plus = string[j+1]
  minus = string[j-1]
  if char == plus or char == minus:
    string.replace(char, "")

For reference, the code SHOULD act as:

input: ppmpvvpmmp output: pmpvmp

But instead, the output does not change at all. Again, I'm aware that this is most likely very easy and I'm overcomplicating, but I'm genuinely struggling here and have tried a lot of similar variations

  • There are conceptually two problems here: first, the code `w.replace(char, "")` **will not change** `w`, but instead creates a **new** string which is then **ignored** by the rest of the code. Second, trying to change the sequence that you are looping over will cause problems with indexing into it. If you want to use this kind of algorithm, instead write it so that you append each value to an output, as you determine what should go into the output. Please see the linked duplicates for more. You can also use a completely different approach (such as regex), but then that's a different question. – Karl Knechtel Nov 24 '22 at 15:51

1 Answers1

0

I would use a regular expression replacement here:

inp = "ppmpvvpmmp"
output = re.sub(r'(\w)\1', r'\1', inp)
print(output)  # pmpvpmp

The above assumes that a duplicate is limited to a single pair of same letters. If instead you want to reduce 3 or more, then use:

inp = "ppmpvvvvvpmmmp"
output = re.sub(r'(\w)\1+', r'\1', inp)
print(output)  # pmpvpmp
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360