I need some help on batteries

Asked

Viewed 57 times

0

I need to create a new list with the values of a string, without repeating the previous digit. If it were only not to put duplicate values, it would be easier, but the rule is not to repeat the previous value.

a = 'AAAABBBCCDAABBB'
b = 'ABBCcAD'
c = [1,2,2,3,3]
pilha = []
for ind, letra in enumerate(a):
    if ind <= 0:
        pilha.append(letra)
    elif len(pilha) > 0:
        pilha.append(letra)
        if letra == pilha[ind-1]:
            pilha.pop()

print(pilha)

These variables are for testing.

  • 1

    This second code doesn’t seem to be related to the question, so it’s just adding noise to it. As for your initial code, it’s a bit strange, especially the condition to run the pop. You’re using the value of ind to check the battery, but ind is the index of your input string. To check whether to pop you must compare with the penultimate value of the stack with pilha[-2]

  • Anderson Carlos Woss, actually replacing the (Ind-1) with the -2 worked. From what I understand, the last would be -1, and the penultimate would be -2. But I really want to understand, as the Ind-1 is out of the range of my stack, since there is an item there. that is the first. Do you have a place where I can get into this? I’m trying to solve these problems that I see on youtube about batteries, to understand better, but from your report, I realize that I’m not leaving the place. Could you give me some feedback? Thank you so much for your time.

  • Do the table test and track the value of ind you will understand.

  • See your code running on Python Tutor to understand where the code error is...

No answers

Browser other questions tagged

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