4 回答

TA貢獻1777條經驗 獲得超3個贊
您正在將每個單詞的most_repeat_count變量重置為0。您應該將代碼中的上部移動到第一個for循環的上方,如下所示:
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貢獻2037條經驗 獲得超6個贊
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貢獻1848條經驗 獲得超6個贊
有趣的練習!使用+1 Counter()。這是我的建議,還利用了max()它的key參數以及*解包運算符。
對于最終解決方案,請注意,此解決方案(以及該問題的其他建議解決方案)當前不考慮大小寫、其他可能的字符(數字、符號等)或是否多個單詞具有最大字母數,或者如果一個單詞將有多個字母且具有最大字母數。
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
添加回答
舉報