Answer the question
In order to leave comments, you need to log in
How to remove all consecutive identical characters in a string in Python?
It's tedious to parse the file and remove all consecutive characters that are repeated 2 times
Input example: wwaldaadicffenn
Output: alice For
some reason my code ignores the daad in the center
arr2 = []
with open("input.txt",'r') as message:
for line in message:
arr = list(line)
for i in arr:
if arr[arr.index(i)] != arr[arr.index(i)+1]:
arr2.append(i)
print(arr2)
Answer the question
In order to leave comments, you need to log in
arr2 = []
with open("input.txt",'r') as message:
for line in message:
arr = list(line)
i = 0
while i < len(arr):
if i == len(arr)-1 or arr[i] != arr[i+1]:
arr2.append(arr[i])
i += 1
else:
i += 2
print(arr2)
import re
s = "wwaldaadicffenn"
regex = re.compile(r"([a-z])\1+")
while True:
if not regex.findall(s):
break
s = regex.sub("", s)
Of course, it turned out not very beautiful, I sketched it in haste, but this function fulfills your request
with open("input.txt",'r', encoding="utf-8") as message:
data = message.read()
arr_str = "55ццуучффвввтиио99аа 1122ткккппрро 33ттаапттоттткккккклммучифффлввосрррь"
def double(arr):
"""
цикл работает до тех пор, пока мы не
убедимся в том, что, идущие подряд символы,
которые повторяются по два раза, были удалены
"""
while True:
arr2 = ""
gap = 0
try:
for i in range(len(arr)):
if arr[i] != arr[i+1]: # если не совпадает символ идем дальше, первый и второй символ
if arr[i] != arr[i-1]: # проверяем первый и перед ним символ
arr2 += arr[i] # если не совпадают записываем
else:
gap += 1
except: # исключение, если в строке нет индекса +1
if arr[i] != arr[i-1]: # проверяем первый и перед ним символ
arr2 += arr[i] # если не совпадают записываем
arr = "" # очищаем строку, для записи новых данных
arr += arr2 # записываем
if gap == 0: # останавливаем цикл, так как дублирующих подряд символов нет
break
return arr
print(double(arr_str))
print(double(data))
A similar problem has already been here
There is a solution using the stack.
With minimal changes, it fits your task.
def del_dup(line):
stack = []
for char in line:
stack.pop() if stack and char == stack[-1] else stack.append(char)
return ''.join(stack)
text = 'wwaldaadicffenn'
print(del_dup(text))
In [4]:
alice
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question