Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python count number of chars in string

Input :

abbbbccdddaaabbbbeeff

Output :

ab4c2d3a3b4e2f2

I have tried like below,

string = 'abbbbccccd'

strList = list(string)
sum = 0

for i , s in enumerate(string):
    # print (strList[i],strList[i+1])

    if strList[i] == strList[i+1]:
        sum = sum + 1
        print(strList[i],'****',sum )

    else:
        sum = sum + 1
        print(strList[i],'****',sum )
        sum = 0

But unable to print the last element from list.

Is there any better way to do it without using any inbuilt functions?

Edit : I wanted to understand the logic of printing abb4c2.. that's why I mentioned without any inbuilt functions. Its ok to use inbuilt functions if the logic can be understandable.

like image 773
Arun Avatar asked Nov 22 '25 10:11

Arun


2 Answers

In those problems, always keep current state (current character & current count). No need for indexes, simpler logic.

And in the end, don't forget to "flush" the current loop data, else you miss the last iteration.

My proposal:

s = "abbbbccdddaaabbbbeeff"

result = []

current = None
current_count = 0


for c in s:
    if current == c:
        current_count += 1
    else:
        if current_count > 1:
            result.append(str(current_count))
        current_count = 1
        current = c
        result.append(c)

# don't forget last iteration count
if current_count > 1:
    result.append(str(current_count))

print("".join(result))

prints:

ab4c2d3a3b4e2f2

Okay, I know "".join(result) invokes a built-in function, but that's the most efficient way. You don't want to append character by character to create the string from the list.

Once you proved that you're mastering such algorithms, use built-ins like itertools.groupby to do such jobs. It's faster and bug-free (or even better: this other answer)

like image 192
Jean-François Fabre Avatar answered Nov 23 '25 23:11

Jean-François Fabre


You could use more_itertools:

from more_itertools import run_length

s = "abbbbccdddaaabbbbeeff"
result = ""
for char, num in run_length.encode(s):
    result += f"{char}{num if num != 1 else ''}"
print(result) #returns ab4c2d3a3b4e2f2

EDIT: missed the part about inbuilt functions. This uses an external library. Leaving it here because I find the initial problem very interesting.

like image 40
fluxens Avatar answered Nov 24 '25 00:11

fluxens