开发者

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:

  • 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.


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


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


Naive implementation:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜