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.
>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!