How to remove duplicates only if consecutive in a

2020-01-26 10:46发布

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.

9条回答
我命由我不由天
2楼-- · 2020-01-26 10:51
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')
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-01-26 10:52

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
查看更多
Melony?
4楼-- · 2020-01-26 10:57
t = '12233322155552'
for i in t:
    dup = i+i
    t = re.sub(dup, i, t)

You can get final output as 1232152

查看更多
何必那么认真
5楼-- · 2020-01-26 10:58

You can use itertools, here is the one liner

>>> s = '12233322155552'
>>> ''.join(i for i, _ in itertools.groupby(s))
'1232152'
查看更多
▲ chillily
6楼-- · 2020-01-26 10:59

This would be a way:

def fix(a):
    list = []

    for element in a:
        # fill the list if the list is empty
        if len(list) == 0:list.append(element)
        # check with the last element of the list
        if list[-1] != element:  list.append(element)

    print(''.join(list))    


a= 'GGGGiiiiniiiGinnaaaaaProtijayi'
fix(a)
# output => GiniGinaProtijayi
查看更多
家丑人穷心不美
7楼-- · 2020-01-26 11:00
number = '12233322155552'
temp_list = []


for item in number:   
   if len(temp_list) == 0:
      temp_list.append(item)

   elif len(temp_list) > 0:
      if  temp_list[-1] != item:
          temp_list.append(item)

print(''.join(temp_list))
查看更多
登录 后发表回答