How to add characters in a string according to a predefined condition?

Asked

Viewed 1,240 times

0

My question is the following, after receiving a string (can be numbers or letters), return this string with the addition of a SE character within this string there are repeated characters in SEQUENCE.

Using Python I know that there are modules like the counter that returns the number of times a character is repeated in a string, but I need to find out if this character is repeated N times in a row.

I thought about solving my problem by going through the user input, turning it into a list, and adding the character after the sequence, but I don’t know if it’s the most pythonic way to do it.

Example:

If the user provides as input "abaabaaaabab".

After the letter "a" repeats 4 times in a row,.

The output would be:

"abaabaaaacbab"

  • 1

    And if the letter "a" is repeated, say 8 times in a row, the output should be "aaaacaaaac" or just "aaaacaaaac"? In the first case I would probably solve the problem with simple substitution (I would replace "aaaa" with "aaaac" until there are no more "aaaa" sequences in the string). In the second case I would go through the String character by adding the characters "a" in a String or temporary list. Whenever you have a character that is not "a", check that the counter is greater than 4, in positive case concaten a "c". In both cases zero the counter.

2 answers

1


Opa Jhonathan, beauty!

Guy according to your question, you want to scroll through a string and find a matching 4-character track and add the letter c after the 4-character. Well when I started studying python I did something similar, so I took that code and adapted it to see if it works for you.

entrada = input('Digite a sequencia ')
lista = []
contador = 0
for i in range(len(entrada)):

    if i+1 < len(entrada):
        if entrada[i] == entrada[i+1] or entrada[i] == entrada[i-1]:

            if contador == 3:
                lista.append(entrada[i])
                lista.append('c')
                contador = 0
                continue

            contador += 1
        else:
            contador = 0     

        lista.append(entrada[i])    
    else:
        if entrada[i] == entrada[i-1] and contador == 3:
            lista.append(entrada[i])
            lista.append('c')
        else:
            lista.append(entrada[i])

output = ''.join(lista)

It is a very simple code, look at it and see the applied logic and try to make changes from this beginning.

1

I implemented the "second case", suggested in Anthony Accioly’s comment.
Please try it, hug!

entrada = "abaabaaaabab"

cont = 0
ant = ""
saida = ""

for c in entrada:    

    saida += c    

    if c == ant:
        cont += 1

    if cont == 4:
        saida += "c"
        cont = 0        

    ant = c

print(saida)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.