views:

80

answers:

3

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

  • descriptions: s 2 , t 1 , n 1
  • statements s 2 , t 3 , n 1

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.

A: 

Naive implementation:

d = {}
for c in s:
  d[c] = s.count(c)
Ignacio Vazquez-Abrams
This would call `.count` too many times. Do you mean `d[c] += 1`?
KennyTM
@KennyTM: That would be part of a non-naive solution.
Ignacio Vazquez-Abrams
@Ignacio : OK .
KennyTM
intuited
@intuited: Sure, that would work.
Ignacio Vazquez-Abrams
+2  A: 

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
KennyTM
+1  A: 
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
ghostdog74
But how to specify whether for example the counts s 2 , t 1 , n 1 belong to 'descriptions' or to 'statements'?
Adia
please see edit. you could have come up with it yourself.
ghostdog74
Thanks. The print should be like this: print k , " for " , s , otherwise would give the error: unsupported operand type(s) for +:
Adia