[英]Return most frequent letter lowercase and in alphabetical order
這是我在互聯網上發現的問題。 mostFrequentLetter(s)接受一個字符串s,並返回一個小寫字符串,其中包含按字母順序排列的最常出現的字母。 應該忽略大小寫(因此對於此函數,“A”和“a”被認為是相同的)。 只考慮字母(沒有標點符號或空格)。 您無需擔心此功能的效率如何。
到目前為止我有這個:
def mostFrequentLetter(s):
s1 = sorted(s)
s1 = s.lower()
for x in s1:
if s1.isAlpha == True:
from collections import Counter
def mostFrequentLetter(s):
mc = Counter(c for c in s.lower() if c.isalpha()).most_common()
return ''.join(sorted(c[0] for c in mc if c[1] == mc[0][1]))
例子:
>>> mostFrequentLetter("ZgVhyaBbv")
'bv'
>>> mostFrequentLetter("aaabbcc????")
'a'
n
個字母 這將在字符串s
提供n
最常用的字母,按字母順序排序:
from collections import Counter
def mostFrequentLetter(s, n=1):
ctr = Counter(c for c in s.lower() if c.isalpha())
return ''.join(sorted(x[0] for x in ctr.most_common(n)))
例子:
>>> mostFrequentLetter('aabbccadef?!', n=1)
'a'
>>> mostFrequentLetter('aabbccadef?!', n=3)
'abc'
c for c in s.lower() if c.isalpha()
這會將字符串s
轉換為小寫,然后只轉換為該字符串中的字母。
ctr = Counter(c for c in s.lower() if c.isalpha())
這會為這些字母創建一個Counter實例。 我們將使用方法most_common
來選擇最常用的字母。 例如,要獲得三個最常見的字母,我們可以使用:
>>> data.most_common(3) [('a', 3), ('c', 2), ('b', 2)]
在我們的例子中,我們對計數不感興趣,只對字母感興趣,所以我們必須操縱這個輸出。
x[0] for x in ctr.most_common(n)
這將選擇n
最常見的字母。
sorted(x[0] for x in ctr.most_common(n))
這按字母順序排列n
最常見的字母。
return ''.join(sorted(x[0] for x in ctr.most_common(n)))
這會將大多數常見字母連接回字符串並返回它們。
如果我們不能使用collections.Counter
,那么試試:
def mostFrequentLetter(s):
d = {}
for c in s.lower():
d[c] = d.get(c, 0) + 1
mx = max(dict_values())
return sorted(c for c, v in d.items() if v == mx)
def mostFrequentLetter(s):
s1 = s.lower()
new = set(s1)
mod={}
for item in new:
if item.isalpha():
mod[item]=s1.count(item)
frequent = sorted (mod,key = mod.get)
return list(reversed(frequent))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.