Adia
Adia

Reputation: 1211

How many times different letters appear in different words?

How to know how many times strings s , t and n appear in each of the following words to have an output like this:

The words are not known in advance.The first thing came to my mind was to make a dictionary, but for dictionaries we can only have two unknowns, so any hints how to approach it? Thanks in advance.

Upvotes: 0

Views: 261

Answers (3)

ghostdog74
ghostdog74

Reputation: 342363

from collections import defaultdict
def counter(STRING):
  h=defaultdict(int)
  for i in STRING:
    if i in "stn":
       h[i]+=1
  return h
for s in ['description','statements']:
    k=counter(s)
    print k + " for " + s

Upvotes: 1

kennytm
kennytm

Reputation: 523274

In Python ≥2.7 and ≥3.1 you could use collections.Counter.

>>> from collections import Counter
>>> Counter("descriptions")
Counter({'i': 2, 's': 2, 'c': 1, 'e': 1, 'd': 1, 'o': 1, 'n': 1, 'p': 1, 'r': 1, 't': 1})

(For Python ≥2.5 there is an implementation in http://code.activestate.com/recipes/576611/.)

The Counter class has the usual dictionary interface, so you could use x['n'] to get the count.

>>> print("%s %s, %s %s, %s %s" % ('s', _['s'], 't', _['t'], 'n', _['n']))
s 2, t 1, n 1

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

Naive implementation:

d = {}
for c in s:
  d[c] = s.count(c)

Upvotes: 0

Related Questions