亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從包含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 關注
  • 258 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號