Skip to content

Commit 2f8e61d

Browse files
committed
add another way to solve the question
1 parent 7b2da8e commit 2f8e61d

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

most_char_num.md

+21-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
特别注意,在字符串中可能会出现数量并列第一的字符,因此要通过循环找出最大数之后,再通过循环找出最大数对应的字母(键)。
1414

15-
#解答
15+
#解答1
1616

1717
import collections
1818

@@ -30,4 +30,24 @@
3030
for char in most_char:
3131
print char
3232

33+
#解答2
34+
35+
str1 = "sdsdsddssssssssdd"
36+
37+
def most_character_number(one_string):
38+
"""利用字典key来统计次数"""
39+
str_dict = {}
40+
for item in one_string:
41+
if item in str_dict:
42+
str_dict[item] +=1
43+
else:
44+
str_dict[item] =1
45+
46+
47+
str_dict = {str_dict[key]:key for key in str_dict}
48+
return (max(str_dict),str_dict[max(str_dict)])
49+
50+
print (most_character_number(str1))
51+
52+
解答2由黄老师提供,[他的微博](http://weibo.com/qiyeminglu)
3353

most_char_num2.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#! /usr/bin/env python
2+
#coding:utf-8
3+
4+
str1 = "jjjjjjddddddllooppxx"
5+
6+
def most_character_number(one_string):
7+
"""利用字典key来统计次数"""
8+
str_dict = {}
9+
for item in one_string:
10+
if item in str_dict:
11+
str_dict[item] +=1
12+
else:
13+
str_dict[item] =1
14+
15+
str_dict = {str_dict[key]:key for key in str_dict}
16+
return (max(str_dict),str_dict[max(str_dict)])
17+
18+
print (most_character_number(str1))

0 commit comments

Comments
 (0)