[英]How do I find the position of the first occurrence of a letter(from the alphabet) in a string?
[英]How do I return the earliest letter in the alphabet from a choice of letters?
我正在做一個練習,要求我用一串字母返回最常用的字母。 如果有兩個字母以相同的頻率出現,則“決勝局”將以字母表中的第一個出現。 例如:
'aaaabbbb' #should return a.
我的回復信的代碼如下。 我認識到它可能不是最有效的。 我以后會擔心的。
def mostWantedLetter(text):
text = text.lower()
mwl = {}
for letter in text:
if letter not in mwl:
mwl[letter] = 1
else:
mwl[letter] += 1
for letter in sorted(mwl, key = mwl.get, reverse = True):
if letter.isalpha():
#letter = sorted(list(letter))
return letter #[0]
感謝Stack Overflow社區幫助我實現這一目標!
祝賀到目前為止。 我會提供兩個提示:
提示1:修改sorted()
的key
參數,以考慮字母的數量及其在字母表中的位置。
提示2:了解Python如何比較元組。
另請注意, collections.Counter
和collections.defaultdict
值得了解。
是的,我發現了這個非常酷:
>>> import collections
>>>
>>> ordered1 = collections.Counter('aaaabbbb').most_common(1))
>>> ordered1[0][0]
'a'
>>>
>>> ordered2 = collections.Counter('abb').most_common(1))
>>> ordered2[0][0]
'b'
這會使字母按順序排列,然后如果兩個字母出現相等的次數,則按字母順序排序。
def mostWantedLetter(text):
# count how many times each letter occurs
mwl = {}
for ch in text.lower():
if ch.isalpha():
mwl[ch] = mwl.get(ch, 0) + 1
# ordered descending by count (highest first) then ascending by letter
least = min(mwl.items(), key=lambda x:(-x[1], x[0]))
# return the letter from the least item
return least[0]
def most_wanted(s):
return chr(min(set([ord(x) for x in list(s)])))
它將字符串分解為一個列表,然后將它們全部轉換為它們的ascii表示。 它使這成為一個集合,因此不需要比較重復項。 它從這些中獲取最小值,然后將其轉換回字母。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.