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
添加回答
举报