hackerrank 中有这样一个题:
给定一个字符串, 输出出现次数最多的前三个字符, 若两字符出现次数相同, 则按字典顺序排列.
# 样例输入 aabbbccde # 样例输出 b 3 a 2 c 2
开始我是这样做的:
from collections import Counter c = Counter(input()) l=sorted(c.items(), key=lambda s:(-s[1], s[0])) for i in l[:3]: print(' '.join(map(str, list(i))))
EDITORIAL给出了三个参考解:
1.利用字母表
S = raw_input() letters = [0]*26 for letter in S: letters[ord(letter)-ord('a')] += 1 for _ in range(3): max_letter = max(letters) for index in range(26): if max_letter == letters[index]: print chr(ord('a')+index), max_letter letters[index] = -1 break
2.
from collections import Counter from operator import itemgetter for item in (sorted(sorted(Counter(raw_input()).items()), key = itemgetter(1), reverse = True)[:3]): print item[0], item[1]
3.
from collections import Counter for letter, counts in sorted(Counter(raw_input()).most_common(),key = lambda x:(-x[1],x[0]))[:3]: print letter, countsmost_common 的行为可能在python 2和3之间不同, 没仔细研究
参考:
http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=429659&id=3140368
http://stackoverflow.com/questions/6666748/python-sort-list-of-lists-ascending-and-then-decending
http://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-criteria