为了账号安全,请及时绑定邮箱和手机立即绑定

从包含python句子的字符串中查找重复字母最多的单词

从包含python句子的字符串中查找重复字母最多的单词

慕桂英4014372 2023-08-22 10:15:58
我想在输入的句子中找到重复字母最多的单词。我知道如何找到句子中重复次数最多的字母,但我无法打印该单词。例如:这是一个基本的测试示例应该打印初级def most_repeating_word(strg):    words =strg.split()    for words1 in words:        dict1 = {}        max_repeat_count = 0        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
查看完整描述

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


查看完整回答
反对 回复 2023-08-22
?
四季花海

TA贡献1811条经验 获得超5个赞

请改用正则表达式。它简单又容易。与正则表达式相比,迭代是一项昂贵的操作。

查看完整回答
反对 回复 2023-08-22
?
阿晨1998

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))


查看完整回答
反对 回复 2023-08-22
?
慕勒3428872

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


查看完整回答
反对 回复 2023-08-22
  • 4 回答
  • 0 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信