Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicates only if consecutive in a string? [duplicate]

For a string such as '12233322155552', by removing the duplicates, I can get '1235'.

But what I want to keep is '1232152', only removing the consecutive duplicates.

like image 728
user1522020 Avatar asked Jul 12 '12 21:07

user1522020


People also ask

How do you find consecutive repeated characters in a string in python?

Given a String, extract all the K-length consecutive characters. Input : test_str = 'geekforgeeeksss is bbbest forrr geeks', K = 3 Output : ['eee', 'sss', 'bbb', 'rrr'] Explanation : K length consecutive strings extracted.


4 Answers

import re

# Only repeated numbers
answer = re.sub(r'(\d)\1+', r'\1', '12233322155552')

# Any repeated character
answer = re.sub(r'(.)\1+', r'\1', '12233322155552')
like image 161
Paulo Freitas Avatar answered Oct 19 '22 23:10

Paulo Freitas


You can use itertools, here is the one liner

>>> s = '12233322155552'
>>> ''.join(i for i, _ in itertools.groupby(s))
'1232152'
like image 21
akash karothiya Avatar answered Oct 19 '22 22:10

akash karothiya


Microsoft / Amazon job interview type of question: This is the pseudocode, the actual code is left as exercise.

for each char in the string do:
   if the current char is equal to the next char:
      delete next char
   else
     continue

return string

As a more high level, try (not actually the implementation):

for s in string:
  if s == s+1:  ## check until the end of the string
     delete s+1
like image 29
cybertextron Avatar answered Oct 20 '22 00:10

cybertextron


Hint: the itertools module is super-useful. One function in particular, itertools.groupby, might come in really handy here:

itertools.groupby(iterable[, key])

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.

So since strings are iterable, what you could do is:

use groupby to collect neighbouring elements
extract the keys from the iterator returned by groupby
join the keys together

which can all be done in one clean line..

like image 44
DSM Avatar answered Oct 19 '22 23:10

DSM