Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my code do not count last string? (Python)

I need to count non-unique sequences going sequentially. For example: "aabcccjaaa" is "21313". But my code do not count the last string. In checks, it goes to the last "else" and must add the last "a" as a unit to the result. What could be the problem? And maybe someone knows a solution instead of mine using standard libraries?

a = "assdddfghttyuuujssa"
b = ''
c = 1
d = []
for item in a:
    if item == b:
        c += 1
    elif b == '':
        c = 1
    else:
        d.append(c)
        c = 1
    b = item

print(d)

I tried to add output of unique words on each iteration of the loop, however it still doesn’t show why the last "append" doesn’t add "1" to the result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your implementation works decently. You’re just getting this error because you don’t add the last item of c when the for-loop ends. Here is your fix:

a = "assdddfghttyuuujssa"
b = ''
c = 1
d = []

for item in a:
    
    if item == b:
        c += 1
    elif b == '':
        c = 1
    else:
        d.append(c)
        c = 1
    b = item

d.append(c) # just added this line
print(d)

I’d recommend in the future to use better naming descriptions for your variable names. This code is quite difficult to unpack and understand since everything is just called a, b, c, … . Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading