Search code examples
count

Fastest way to count contiguously chars


I have a text string like:

33 P DDD AA 00 23

I've created a code that works well, but I'm searching for other methods to do that.

translate_dict = {
   ...
}    

result = []
i = 0

while i < len(t):
    counter = 1
    while i+counter < len(t) and t[i] == t[i+counter]:
        counter +=1
    result.append(translate_dict.get(t[i], t[i]) + str(counter))
    i += counter
    
return ''.join(result)

Solution

  • Here's one possible optimization:

    def f2(t):
        res = []
        last = t[0]
        counter = 0
        duration = 0
        tr = translate_dict.get
    
        for c in t:
            if c == last:
                counter += 1
                continue
            res.append(tr(last, last) + str(counter))
            duration += counter
            last = c
            counter = 1
    
        res.append(tr(last, last) + str(counter))
        duration += counter
    
        return ''.join(res), duration
    

    Shows ~ 2x improvement on my machine.