字符计数问题
这里有个字符串
'here is a sample of english text'
问里面各个字符出现次数是多少

 

要求返回结果: (字典是无序的, 所以只要结果正确, 不要求顺序如此)
{'a': 2, ' ': 6, 'e': 5, 'g': 1, 'f': 1, 'i': 2, 'h': 2, 'm': 1, 'l': 2, 'o': 1, 'n': 1, 'p': 1, 's': 3, 'r': 1, 't': 2, 'x': 1} 

 

代码:

代码
#!/usr/bin/env python
#
count the number of each character

def CouChar(str):
d
= {}
for s in str:
if s in d:
d[s]
= d[s] + 1
else:
d[s]
= 1
print d

if __name__ == "__main__":
str
= "here is a sample of english text"
CouChar(str)

 

 

更多解法参考:

tieba.baidu.com/f?kz=627003001

posted on 2010-09-14 22:23  oyzway  阅读(336)  评论(0编辑  收藏  举报