查找出现次数最多的字符及其计数的Python程序
给定一个字符串,编写一个Python程序来查找出现次数最多的字符及其出现次数。
例子:
Input : hello
Output : ('l', 2)
Input : geeksforgeeks
Output : ('e', 4)
我们可以在Python中使用 Counter() 方法快速解决这个问题。简单的方法是
1) 使用 Counter 方法创建一个字典,将字符串作为键,将它们的频率作为值。
2) 找出一个字符的最大出现次数,即值并得到它的索引。
# Python program to find the most occurring
# character and its count
from collections import Counter
def find_most_occ_char(input):
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
wc = Counter(input)
# Finding maximum occurrence of a character
# and get the index of it.
s = max(wc.values())
i = wc.values().index(s)
print wc.items()[i]
# Driver program
if __name__ == "__main__":
input = 'geeksforgeeks'
find_most_occ_char(input)
输出:
('e', 4)