Arun
Arun

Reputation: 831

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.

Upvotes: 2

Views: 166

Answers (3)

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

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)

Upvotes: 6

fluxens
fluxens

Reputation: 565

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.

Upvotes: 2

nikhildr22
nikhildr22

Reputation: 100

You can use dictionaries

a='abbbbccdddaaabbbbeeff'
d=dict()
for i in a:
      if i not in d:d[i]=1
      else:d[i]+=1
for key,value in d.items():
    print(key,value,sep='',end='')

output a4b8c2d3e2f2

Upvotes: 0

Related Questions