字符计数问题
这里有个字符串
'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}
代码:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#
!/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)
# 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)
更多解法参考: