4 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個(gè)贊
您正在將每個(gè)單詞的most_repeat_count變量重置為0。您應(yīng)該將代碼中的上部移動(dòng)到第一個(gè)for循環(huán)的上方,如下所示:
def most_repeating_word(strg):
words =strg.split()
max_repeat_count = 0
for words1 in words:
dict1 = {}
for letter in words1:
if letter not in dict1:
dict1[letter] = 1
else:
dict1[letter] += 1
if dict1[letter]> max_repeat_count:
max_repeat_count = dict1[letter]
most_repeated_char = letter
result=words1
return result

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
word="SBDDUKRWZHUYLRVLIPVVFYFKMSVLVEQTHRUOFHPOALGXCNLXXGUQHQVXMRGVQTBEYVEGMFD"
def most_repeating_word(strg):
dict={}
max_repeat_count = 0
for word in strg:
if word not in dict:
dict[word] = 1
else:
dict[word] += 1
if dict[word]> max_repeat_count:
max_repeat_count = dict[word]
result={}
for word, value in dict.items():
if value==max_repeat_count:
result[word]=value
return result
print(most_repeating_word(word))

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
有趣的練習(xí)!使用+1 Counter()。這是我的建議,還利用了max()它的key參數(shù)以及*解包運(yùn)算符。
對于最終解決方案,請注意,此解決方案(以及該問題的其他建議解決方案)當(dāng)前不考慮大小寫、其他可能的字符(數(shù)字、符號(hào)等)或是否多個(gè)單詞具有最大字母數(shù),或者如果一個(gè)單詞將有多個(gè)字母且具有最大字母數(shù)。
from collections import Counter
def most_repeating_word(strg):
# Create list of word tuples: (word, max_letter, max_count)
counters = [ (word, *max(Counter(word).items(), key=lambda item: item[1]))
for word in strg.split() ]
max_word, max_letter, max_count = max(counters, key=lambda item: item[2])
return max_word
添加回答
舉報(bào)