-1

I'm currently trying to solve a problem of counting repeating characters in a row in Python.

This code works until it comes to the last different character in a string, and I have no idea how to solve this problem

def repeating(word): 
    count=1
    tmp = ""
    res = {}
    for i in range(1, len(word)):
        tmp += word[i - 1]
        if word[i - 1] == word[i]:
            count += 1
        else :
            res[tmp] = count
            count = 1
            tmp = ""

    return res

word="aabc"
print (repeating(word))

The given output should be {'aa': 2, 'b': 1, 'c' : 1}, but I am getting {'aa': 2, 'b': 1}

How do I solve this?

  • Indexing in Python (and most languages) start from `0`. Change to `range(len(word))`. – jpp Nov 14 '18 at 13:48
  • What exactly do you mean by repeating characters? Same character appearing successively in the string? What should the output be for `abcadaeb`? – Silver Nov 14 '18 at 13:48
  • As per marked dup, `range(x, y)` starts from `x`, not `x-1`, and indexing begins at 0. – jpp Nov 14 '18 at 13:52

2 Answers2

0

I would recommend using Counter from the collections module. It does exactly what you are trying to achieve

from collections import Counter

wourd = "aabc"
print(Counter(word))
# Counter({'a': 2, 'b': 1, 'c': 1})

But if you want to implement it yourself, I should know that str is an Iterable. Hence you are able to iterate over every letter with a simple loop.

Additionally, there is something called defaultdict, which comes quite handy in this scenario. Normally you have to check whether a key (in this case a letter) is already defined. If not you have to create that key. If you are using a defaultdict, you can define that every new key has a default value of something.

from collections import defaultdict

def repeating(word):
    counter = defaultdict(int)
    for letter in word:
       counter[letter] += 1
    return counter

The result would be similar:

In [6]: repeating('aabc')
Out[6]: defaultdict(int, {'a': 2, 'b': 1, 'c': 1}) 
escaped
  • 734
  • 4
  • 10
0

In this case, you can use the collections.Counter which does all the work for you.

>>> from collections import Counter
>>> Counter('aabc')
Counter({'a': 2, 'c': 1, 'b': 1})

You can also iterator over the letters in string, since this is iterable. But then I would use the defaultdict from collections to save on the 'counting' part.

>>> from collections import defaultdict
>>> 
>>> def repeating(word): 
...     res = defaultdict(int)
...     for letter in word:
...         res[letter] +=1
...     return res
... 
>>> word="aabc"
>>> print (repeating(word))
defaultdict(<type 'int'>, {'a': 2, 'c': 1, 'b': 1})
The Pjot
  • 1,801
  • 1
  • 12
  • 20