查找字符串中出现频率最高的字符

发布于 2024-09-30 22:54:58 字数 1068 浏览 6 评论 0原文

我在查看 SO 上的职位发布时发现了这个编程问题。我认为这非常有趣,作为一名 Python 初学者,我尝试解决它。然而我觉得我的解决方案相当......混乱......任何人都可以提出任何建议来优化它或使其更干净吗?我知道这很琐碎,但我写得很开心。注意:Python 2.6

问题:

为接受字符串并返回该字符串中出现次数最多的字母的函数编写伪代码(或实际代码)。

我的尝试:

import string

def find_max_letter_count(word):

    alphabet = string.ascii_lowercase
    dictionary = {}

    for letters in alphabet:
        dictionary[letters] = 0

    for letters in word:
        dictionary[letters] += 1

    dictionary = sorted(dictionary.items(), 
                        reverse=True, 
                        key=lambda x: x[1])

    for position in range(0, 26):
        print dictionary[position]
        if position != len(dictionary) - 1:
            if dictionary[position + 1][1] < dictionary[position][1]:
                break

find_max_letter_count("helloworld")

输出:

>>> 
('l', 3)

更新的示例:

find_max_letter_count("balloon") 
>>>
('l', 2)
('o', 2)

I found this programming problem while looking at a job posting on SO. I thought it was pretty interesting and as a beginner Python programmer I attempted to tackle it. However I feel my solution is quite...messy...can anyone make any suggestions to optimize it or make it cleaner? I know it's pretty trivial, but I had fun writing it. Note: Python 2.6

The problem:

Write pseudo-code (or actual code) for a function that takes in a string and returns the letter that appears the most in that string.

My attempt:

import string

def find_max_letter_count(word):

    alphabet = string.ascii_lowercase
    dictionary = {}

    for letters in alphabet:
        dictionary[letters] = 0

    for letters in word:
        dictionary[letters] += 1

    dictionary = sorted(dictionary.items(), 
                        reverse=True, 
                        key=lambda x: x[1])

    for position in range(0, 26):
        print dictionary[position]
        if position != len(dictionary) - 1:
            if dictionary[position + 1][1] < dictionary[position][1]:
                break

find_max_letter_count("helloworld")

Output:

>>> 
('l', 3)

Updated example:

find_max_letter_count("balloon") 
>>>
('l', 2)
('o', 2)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

明月松间行 2024-10-07 22:54:58

有很多方法可以缩短这个时间。例如,您可以使用 计数器 类(在 Python 2.7 或更高版本中):

import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])

如果你没有这个,你可以手动进行计数(2.5 或更高版本有 defaultdict):

d = collections.defaultdict(int)
for c in s:
    d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])

话虽如此,没有什么太可怕的错误你的实施。

There are many ways to do this shorter. For example, you can use the Counter class (in Python 2.7 or later):

import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])

If you don't have that, you can do the tally manually (2.5 or later has defaultdict):

d = collections.defaultdict(int)
for c in s:
    d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])

Having said that, there's nothing too terribly wrong with your implementation.

傲影 2024-10-07 22:54:58

如果您使用的是 Python 2.7,则可以使用 collections 模块快速完成此操作。
Collections 是一个高性能数据结构模块。阅读更多内容
http://docs.python.org/library/collections.html#counter-objects

>>> from collections import Counter
>>> x = Counter("balloon")
>>> x
Counter({'o': 2, 'a': 1, 'b': 1, 'l': 2, 'n': 1})
>>> x['o']
2

If you are using Python 2.7, you can quickly do this by using collections module.
collections is a hight performance data structures module. Read more at
http://docs.python.org/library/collections.html#counter-objects

>>> from collections import Counter
>>> x = Counter("balloon")
>>> x
Counter({'o': 2, 'a': 1, 'b': 1, 'l': 2, 'n': 1})
>>> x['o']
2
陪你到最终 2024-10-07 22:54:58

这是使用字典查找最常见字符的方法

message = "hello world"
d = {}
letters = set(message)
for l in letters:
    d[message.count(l)] = l

print d[d.keys()[-1]], d.keys()[-1]

Here is way to find the most common character using a dictionary

message = "hello world"
d = {}
letters = set(message)
for l in letters:
    d[message.count(l)] = l

print d[d.keys()[-1]], d.keys()[-1]
醉生梦死 2024-10-07 22:54:58

这是使用 FOR LOOP AND COUNT() 的方法

w = input()
r = 1
for i in w:
    p = w.count(i)
    if p > r:
        r = p
        s = i
print(s)

Here's a way using FOR LOOP AND COUNT()

w = input()
r = 1
for i in w:
    p = w.count(i)
    if p > r:
        r = p
        s = i
print(s)
走野 2024-10-07 22:54:58

我的方法不使用 Python 本身的内置函数,只使用 for 循环和 if 语句。

def most_common_letter():
    string = str(input())
    letters = set(string)
    if " " in letters:         # If you want to count spaces too, ignore this if-statement
        letters.remove(" ")
    max_count = 0
    freq_letter = []
    for letter in letters:
        count = 0
        for char in string:
            if char == letter:
                count += 1
        if count == max_count:
            max_count = count
            freq_letter.append(letter)
        if count > max_count:
            max_count = count
            freq_letter.clear()
            freq_letter.append(letter)
    return freq_letter, max_count

这可确保您获得最常用的每个字母/字符,而不仅仅是一个。它还返回它发生的频率。希望这有帮助:)

The way I did uses no built-in functions from Python itself, only for-loops and if-statements.

def most_common_letter():
    string = str(input())
    letters = set(string)
    if " " in letters:         # If you want to count spaces too, ignore this if-statement
        letters.remove(" ")
    max_count = 0
    freq_letter = []
    for letter in letters:
        count = 0
        for char in string:
            if char == letter:
                count += 1
        if count == max_count:
            max_count = count
            freq_letter.append(letter)
        if count > max_count:
            max_count = count
            freq_letter.clear()
            freq_letter.append(letter)
    return freq_letter, max_count

This ensures you get every letter/character that gets used the most, and not just one. It also returns how often it occurs. Hope this helps :)

兔姬 2024-10-07 22:54:58

如果您想让所有字符具有最大计数,那么您可以对目前提出的两个想法之一进行变体:

import heapq  # Helps finding the n largest counts
import collections

def find_max_counts(sequence):
    """
    Returns an iterator that produces the (element, count)s with the
    highest number of occurrences in the given sequence.

    In addition, the elements are sorted.
    """

    if len(sequence) == 0:
        raise StopIteration

    counter = collections.defaultdict(int)
    for elmt in sequence:
        counter[elmt] += 1

    counts_heap = [
        (-count, elmt)  # The largest elmt counts are the smallest elmts
        for (elmt, count) in counter.iteritems()]

    heapq.heapify(counts_heap)

    highest_count = counts_heap[0][0]

    while True:

        try:
            (opp_count, elmt) = heapq.heappop(counts_heap)
        except IndexError:
            raise StopIteration

        if opp_count != highest_count:
            raise StopIteration

        yield (elmt, -opp_count)

for (letter, count) in find_max_counts('balloon'):
    print (letter, count)

for (word, count) in find_max_counts(['he', 'lkj', 'he', 'll', 'll']):
    print (word, count)

例如,这会产生:

lebigot@weinberg /tmp % python count.py
('l', 2)
('o', 2)
('he', 2)
('ll', 2)

这适用于任何序列:单词,还有 ['hello', 'hello', 'bonjour'],例如。

heapq 结构非常有效地查找序列中的最小元素,而无需对其进行完全排序。另一方面,由于字母表中没有那么多字母,您也可以遍历排序的计数列表,直到不再找到最大计数,而不会导致任何严重的速度损失。

If you want to have all the characters with the maximum number of counts, then you can do a variation on one of the two ideas proposed so far:

import heapq  # Helps finding the n largest counts
import collections

def find_max_counts(sequence):
    """
    Returns an iterator that produces the (element, count)s with the
    highest number of occurrences in the given sequence.

    In addition, the elements are sorted.
    """

    if len(sequence) == 0:
        raise StopIteration

    counter = collections.defaultdict(int)
    for elmt in sequence:
        counter[elmt] += 1

    counts_heap = [
        (-count, elmt)  # The largest elmt counts are the smallest elmts
        for (elmt, count) in counter.iteritems()]

    heapq.heapify(counts_heap)

    highest_count = counts_heap[0][0]

    while True:

        try:
            (opp_count, elmt) = heapq.heappop(counts_heap)
        except IndexError:
            raise StopIteration

        if opp_count != highest_count:
            raise StopIteration

        yield (elmt, -opp_count)

for (letter, count) in find_max_counts('balloon'):
    print (letter, count)

for (word, count) in find_max_counts(['he', 'lkj', 'he', 'll', 'll']):
    print (word, count)

This yields, for instance:

lebigot@weinberg /tmp % python count.py
('l', 2)
('o', 2)
('he', 2)
('ll', 2)

This works with any sequence: words, but also ['hello', 'hello', 'bonjour'], for instance.

The heapq structure is very efficient at finding the smallest elements of a sequence without sorting it completely. On the other hand, since there are not so many letter in the alphabet, you can probably also run through the sorted list of counts until the maximum count is not found anymore, without this incurring any serious speed loss.

孤檠 2024-10-07 22:54:58
def most_frequent(text):
    frequencies = [(c, text.count(c)) for c in set(text)]
    return max(frequencies, key=lambda x: x[1])[0]

s = 'ABBCCCDDDD'
print(most_frequent(s))

frequencies 是一个元组列表,将字符计数为 (character, count)。我们使用 count 将 max 应用于元组,并返回该元组的字符。如果出现平局,该解决方案将只选择一个。

def most_frequent(text):
    frequencies = [(c, text.count(c)) for c in set(text)]
    return max(frequencies, key=lambda x: x[1])[0]

s = 'ABBCCCDDDD'
print(most_frequent(s))

frequencies is a list of tuples that count the characters as (character, count). We apply max to the tuples using count's and return that tuple's character. In the event of a tie, this solution will pick only one.

盗琴音 2024-10-07 22:54:58

我注意到大多数答案只返回一项,即使最常用的字符数量相同。例如“iii 444 yyy 999”。有相同数量的空格、i、4、y 和 9。解决方案应该包含所有内容,而不仅仅是字母 i:

sentence = "iii 444 yyy 999"

# Returns the first items value in the list of tuples (i.e) the largest number
# from Counter().most_common()
largest_count: int = Counter(sentence).most_common()[0][1]

# If the tuples value is equal to the largest value, append it to the list
most_common_list: list = [(x, y)
                         for x, y in Counter(sentence).items() if y == largest_count]

print(most_common_count)

# RETURNS
[('i', 3), (' ', 3), ('4', 3), ('y', 3), ('9', 3)]

I noticed that most of the answers only come back with one item even if there is an equal amount of characters most commonly used. For example "iii 444 yyy 999". There are an equal amount of spaces, i's, 4's, y's, and 9's. The solution should come back with everything, not just the letter i:

sentence = "iii 444 yyy 999"

# Returns the first items value in the list of tuples (i.e) the largest number
# from Counter().most_common()
largest_count: int = Counter(sentence).most_common()[0][1]

# If the tuples value is equal to the largest value, append it to the list
most_common_list: list = [(x, y)
                         for x, y in Counter(sentence).items() if y == largest_count]

print(most_common_count)

# RETURNS
[('i', 3), (' ', 3), ('4', 3), ('y', 3), ('9', 3)]
只是偏爱你 2024-10-07 22:54:58

问题 :
字符串中出现次数最多的字符
输入字符串中出现的最多字符

方法 1 :

a = "GiniGinaProtijayi"

d ={}
chh = ''
max = 0 
for ch in a : d[ch] = d.get(ch,0) +1 
for val in sorted(d.items(),reverse=True , key = lambda ch : ch[1]):
    chh = ch
    max  = d.get(ch)
    
    
print(chh)  
print(max)  

方法 2 :

a = "GiniGinaProtijayi"

max = 0 
chh = ''
count = [0] * 256 
for ch in a : count[ord(ch)] += 1
for ch in a :
    if(count[ord(ch)] > max):
        max = count[ord(ch)] 
        chh = ch
        
print(chh)        

方法 3 :

   import collections
    
    line ='North Calcutta Shyambazaar Soudipta Tabu  Roopa Roopi Gina Gini Protijayi  Sovabazaar Paikpara  Baghbazaar  Roopa'
    
bb = collections.Counter(line).most_common(1)[0][0]
print(bb)

方法 4 :

line =' North Calcutta Shyambazaar Soudipta Tabu  Roopa Roopi Gina Gini Protijayi  Sovabazaar Paikpara  Baghbazaar  Roopa'


def mostcommonletter(sentence):
    letters = list(sentence)
    return (max(set(letters),key = letters.count))


print(mostcommonletter(line))    

    

Question :
Most frequent character in a string
The maximum occurring character in an input string

Method 1 :

a = "GiniGinaProtijayi"

d ={}
chh = ''
max = 0 
for ch in a : d[ch] = d.get(ch,0) +1 
for val in sorted(d.items(),reverse=True , key = lambda ch : ch[1]):
    chh = ch
    max  = d.get(ch)
    
    
print(chh)  
print(max)  

Method 2 :

a = "GiniGinaProtijayi"

max = 0 
chh = ''
count = [0] * 256 
for ch in a : count[ord(ch)] += 1
for ch in a :
    if(count[ord(ch)] > max):
        max = count[ord(ch)] 
        chh = ch
        
print(chh)        

Method 3 :

   import collections
    
    line ='North Calcutta Shyambazaar Soudipta Tabu  Roopa Roopi Gina Gini Protijayi  Sovabazaar Paikpara  Baghbazaar  Roopa'
    
bb = collections.Counter(line).most_common(1)[0][0]
print(bb)

Method 4 :

line =' North Calcutta Shyambazaar Soudipta Tabu  Roopa Roopi Gina Gini Protijayi  Sovabazaar Paikpara  Baghbazaar  Roopa'


def mostcommonletter(sentence):
    letters = list(sentence)
    return (max(set(letters),key = letters.count))


print(mostcommonletter(line))    

    
栖竹 2024-10-07 22:54:58

以下是我要做的一些事情:

  • 使用 collections.defaultdict 而不是您手动初始化的 dict
  • 使用内置排序和 max 函数(例如 max),而不是自己计算 - 这更容易。

这是我的最终结果:

from collections import defaultdict

def find_max_letter_count(word):
    matches = defaultdict(int)  # makes the default value 0

    for char in word:
        matches[char] += 1

    return max(matches.iteritems(), key=lambda x: x[1])

find_max_letter_count('helloworld') == ('l', 3)

Here are a few things I'd do:

  • Use collections.defaultdict instead of the dict you initialise manually.
  • Use inbuilt sorting and max functions like max instead of working it out yourself - it's easier.

Here's my final result:

from collections import defaultdict

def find_max_letter_count(word):
    matches = defaultdict(int)  # makes the default value 0

    for char in word:
        matches[char] += 1

    return max(matches.iteritems(), key=lambda x: x[1])

find_max_letter_count('helloworld') == ('l', 3)
ぃ双果 2024-10-07 22:54:58

如果您因任何原因无法使用集合,我建议采用以下实现:

s = input()
d = {}

# We iterate through a string and if we find the element, that
# is already in the dict, than we are just incrementing its counter.
for ch in s:
    if ch in d:
        d[ch] += 1
    else:
        d[ch] = 1

# If there is a case, that we are given empty string, then we just
# print a message, which says about it.
print(max(d, key=d.get, default='Empty string was given.'))

If you could not use collections for any reason, I would suggest the following implementation:

s = input()
d = {}

# We iterate through a string and if we find the element, that
# is already in the dict, than we are just incrementing its counter.
for ch in s:
    if ch in d:
        d[ch] += 1
    else:
        d[ch] = 1

# If there is a case, that we are given empty string, then we just
# print a message, which says about it.
print(max(d, key=d.get, default='Empty string was given.'))
爱,才寂寞 2024-10-07 22:54:58
sentence = "This is a great question made me wanna watch matrix again!"

char_frequency = {}

for char in sentence:
    if char == " ": #to skip spaces
        continue
    elif char in char_frequency:
        char_frequency[char] += 1 
    else:
        char_frequency[char] = 1


char_frequency_sorted = sorted(
    char_frequency.items(), key=lambda ky: ky[1], reverse=True
)
print(char_frequency_sorted[0]) #output -->('a', 9)
sentence = "This is a great question made me wanna watch matrix again!"

char_frequency = {}

for char in sentence:
    if char == " ": #to skip spaces
        continue
    elif char in char_frequency:
        char_frequency[char] += 1 
    else:
        char_frequency[char] = 1


char_frequency_sorted = sorted(
    char_frequency.items(), key=lambda ky: ky[1], reverse=True
)
print(char_frequency_sorted[0]) #output -->('a', 9)
入怼 2024-10-07 22:54:58
# return the letter with the max frequency.

def maxletter(word:str) -> tuple:
    ''' return the letter with the max occurance '''
    v = 1
    dic = {}
    for letter in word:
        if letter in dic:
            dic[letter] += 1
        else:
            dic[letter] = v

    for k in dic:
        if dic[k] == max(dic.values()):
            return k, dic[k]

l, n = maxletter("Hello World")
print(l, n)

输出:l 3

# return the letter with the max frequency.

def maxletter(word:str) -> tuple:
    ''' return the letter with the max occurance '''
    v = 1
    dic = {}
    for letter in word:
        if letter in dic:
            dic[letter] += 1
        else:
            dic[letter] = v

    for k in dic:
        if dic[k] == max(dic.values()):
            return k, dic[k]

l, n = maxletter("Hello World")
print(l, n)

output: l 3

萌面超妹 2024-10-07 22:54:58

您也可以尝试以下操作。

from pprint import pprint                               
    sentence = "this is a common interview question"        
                                                            
    char_frequency = {}                                     
    for char in sentence:                                   
        if char in char_frequency:                          
            char_frequency[char] += 1                       
        else:                                               
            char_frequency[char] = 1                        
    pprint(char_frequency, width = 1)                       
    out = sorted(char_frequency.items(),                    
                 key = lambda kv : kv[1], reverse = True)   
    print(out)                                              
    print(out[0])   

you may also try something below.

from pprint import pprint                               
    sentence = "this is a common interview question"        
                                                            
    char_frequency = {}                                     
    for char in sentence:                                   
        if char in char_frequency:                          
            char_frequency[char] += 1                       
        else:                                               
            char_frequency[char] = 1                        
    pprint(char_frequency, width = 1)                       
    out = sorted(char_frequency.items(),                    
                 key = lambda kv : kv[1], reverse = True)   
    print(out)                                              
    print(out[0])   
撩人痒 2024-10-07 22:54:58

统计.模式(数据)
从离散或标称数据中返回单个最常见的数据点。众数(如果存在)是最典型的值,可用作中心位置的度量。

如果存在具有相同频率的多个模式,则返回数据中遇到的第一个模式。如果需要其中最小或最大的值,请使用 min(multimode(data)) 或 max(multimode(data))。如果输入数据为空,则会引发统计错误。

import statistics as stat

test = 'This is a test of the fantastic mode super special function ssssssssssssss'
test2 = ['block', 'cheese', 'block']
val = stat.mode(test)
val2 = stat.mode(test2)
print(val, val2)

模式假定离散数据并返回单个值。这是学校中通常教授的模式的标准处理方法:

mode([1, 1, 2, 3, 3, 3, 3, 4])
3

该模式的独特之处在于它是此包中唯一也适用于名义(非数字)数据的统计数据:

mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'

statistics.mode(data)
Return the single most common data point from discrete or nominal data. The mode (when it exists) is the most typical value and serves as a measure of central location.

If there are multiple modes with the same frequency, returns the first one encountered in the data. If the smallest or largest of those is desired instead, use min(multimode(data)) or max(multimode(data)). If the input data is empty, StatisticsError is raised.

import statistics as stat

test = 'This is a test of the fantastic mode super special function ssssssssssssss'
test2 = ['block', 'cheese', 'block']
val = stat.mode(test)
val2 = stat.mode(test2)
print(val, val2)

mode assumes discrete data and returns a single value. This is the standard treatment of the mode as commonly taught in schools:

mode([1, 1, 2, 3, 3, 3, 3, 4])
3

The mode is unique in that it is the only statistic in this package that also applies to nominal (non-numeric) data:

mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
烟凡古楼 2024-10-07 22:54:58

考虑到多个最常见字符的可能性,这是我解决这个问题的方法:

sentence = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut 
enim."

joint_sentence = sentence.replace(" ", "")
frequencies = {}
for letter in joint_sentence:
    frequencies[letter] = frequencies.get(letter, 0) +1

biggest_frequency = frequencies[max(frequencies, key=frequencies.get)]
most_frequent_letters = {key: value for key, value in frequencies.items() if value == biggest_frequency}
print(most_frequent_letters)

输出:

{'e': 12, 'i': 12}

Here is how I solved it, considering the possibility of multiple most frequent chars:

sentence = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut 
enim."

joint_sentence = sentence.replace(" ", "")
frequencies = {}
for letter in joint_sentence:
    frequencies[letter] = frequencies.get(letter, 0) +1

biggest_frequency = frequencies[max(frequencies, key=frequencies.get)]
most_frequent_letters = {key: value for key, value in frequencies.items() if value == biggest_frequency}
print(most_frequent_letters)

Output:

{'e': 12, 'i': 12}
冷了相思 2024-10-07 22:54:58

#来自与 Mosh 一起编码
从 pprint 导入 pprint
句子=“你好世界”

char_frequency = {}
for char in sentence:
    if char in char_frequency:
        char_frequency[char] += 1
    else:
        char_frequency[char] = 1

char_frequency_sorted = sorted(
    char_frequency.items(),
    key=lambda kv: kv[1],
    reverse=True)
print(char_frequency_sorted[0])

#from Coding with Mosh
from pprint import pprint
sentence = "Hello World"

char_frequency = {}
for char in sentence:
    if char in char_frequency:
        char_frequency[char] += 1
    else:
        char_frequency[char] = 1

char_frequency_sorted = sorted(
    char_frequency.items(),
    key=lambda kv: kv[1],
    reverse=True)
print(char_frequency_sorted[0])
最单纯的乌龟 2024-10-07 22:54:58
#file:filename
#quant:no of frequent words you want

def frequent_letters(file,quant):
    file = open(file)
    file = file.read()
    cnt = Counter
    op = cnt(file).most_common(quant)
    return op   
#file:filename
#quant:no of frequent words you want

def frequent_letters(file,quant):
    file = open(file)
    file = file.read()
    cnt = Counter
    op = cnt(file).most_common(quant)
    return op   
微凉 2024-10-07 22:54:58
# This code is to print all characters in a string which have highest frequency
 
def find(str):
      
    y = sorted([[a.count(i),i] for i in set(str)])
  # here,the count of unique character and the character are taken as a list  
  # inside y(which is a list). And they are sorted according to the 
  # count of each character in the list y. (ascending)
  # Eg : for "pradeep", y = [[1,'r'],[1,'a'],[1,'d'],[2,'p'],[2,'e']]

    most_freq= y[len(y)-1][0]   
  # the count of the most freq character is assigned to the variable 'r'
  # ie, most_freq= 2

    x= []

    for j in range(len(y)):
       
        if y[j][0] == most_freq:
            x.append(y[j])
      # if the 1st element in the list of list == most frequent 
      # character's count, then all the characters which have the 
      # highest frequency will be appended to list x.
      # eg :"pradeep"
      # x = [['p',2],['e',2]]   O/P  as expected
    return x

find("pradeep")
# This code is to print all characters in a string which have highest frequency
 
def find(str):
      
    y = sorted([[a.count(i),i] for i in set(str)])
  # here,the count of unique character and the character are taken as a list  
  # inside y(which is a list). And they are sorted according to the 
  # count of each character in the list y. (ascending)
  # Eg : for "pradeep", y = [[1,'r'],[1,'a'],[1,'d'],[2,'p'],[2,'e']]

    most_freq= y[len(y)-1][0]   
  # the count of the most freq character is assigned to the variable 'r'
  # ie, most_freq= 2

    x= []

    for j in range(len(y)):
       
        if y[j][0] == most_freq:
            x.append(y[j])
      # if the 1st element in the list of list == most frequent 
      # character's count, then all the characters which have the 
      # highest frequency will be appended to list x.
      # eg :"pradeep"
      # x = [['p',2],['e',2]]   O/P  as expected
    return x

find("pradeep")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文