Counting consecutive characters in a string

14,597

Solution 1

Use Collections.Counter(), dictionary is a better way to store this:

>>> from collections import Counter
>>> strs="assassin"
>>> Counter(strs)
Counter({'s': 4, 'a': 2, 'i': 1, 'n': 1})

or using itertools.groupby():

>>> [[k, len(list(g))] for k, g in groupby(strs)]
[['a', 1], ['s', 2], ['a', 1], ['s', 2], ['i', 1], ['n', 1]]

Solution 2

last = ''
results = []
word = 'assassin'
for letter in word:
if letter == last:
    results[-1] = (letter, results[-1][1] +1)
else:
    results.append((letter, 1))
    last = letter

print result # [('a', 1), ('s', 2), ('a', 1), ('s', 2), ('i', 1), ('n', 1)]

Solution 3

Using only builtins:

def cnt(s):
    current = [s[0],1]
    out = [current]
    for c in s[1:]:
        if c == current[0]:
            current[1] += 1
        else:
            current = [c, 1]
            out.append(current)
    return out

print cnt('assassin')
Share:
14,597
Spectalecy
Author by

Spectalecy

Updated on June 21, 2022

Comments

  • Spectalecy
    Spectalecy almost 2 years

    I need to write a code that slices the string (which is an input), append it to a list, count the number of each letter - and if it is identical to the letter before it, don't put it in the list, but rather increase the appearance number of that letter in the one before.. Well this is how it should look like :

    assassin [['a', 1], ['s', 2], ['a', 1], ['s', 2]], ['i', 1], ['n', 1]
    

    the word assassin is just an example of the need.. My code so far goes like this:

    userin = raw_input("Please enter a string :")
    inputlist = []
    inputlist.append(userin)
    biglist = []
    i=0
    count = {}
    while i<(len(userin)):
        slicer = inputlist[0][i]
        for s in userin:
            if count.has_key(s):
                count[s] += 1
            else:
                count[s] = 1
        biglist.append([slicer,s])
        i = i+1
    print biglist 
    

    Thanks!