HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Counting letters in a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stringcountingletters

Problem

This little program is self-explanatory. I count letters in a string (can be any string), using a for loop to iterate through each letter. The problem is that this method is very slow and I want to avoid loops.

Any ideas? I thought that maybe if I remove checked letters from the string after each loop, then in some cases, where many letters repeat, that would make a difference.

def count_dict(mystring):
    d = {}
# count occurances of character
    for w in mystring: 
        d[w] = mystring.count(w)
# print the result
    for k in sorted(d):
        print (k + ': ' + str(d[k]))

mystring='qwertyqweryyyy'
count_dict(mystring)


The output:

e: 2
q: 2
r: 2
t: 1
w: 2
y: 5

Solution

Use the built in Counter in the collections module:

>>> from collections import Counter
>>> Counter('qwertyqweryyyy')
Counter({'y': 5, 'e': 2, 'q': 2, 'r': 2, 'w': 2, 't': 1})

Code Snippets

>>> from collections import Counter
>>> Counter('qwertyqweryyyy')
Counter({'y': 5, 'e': 2, 'q': 2, 'r': 2, 'w': 2, 't': 1})

Context

StackExchange Code Review Q#27781, answer score: 14

Revisions (0)

No revisions yet.