【问题标题】:Print the maximum occurence of the anagrams and the anagram words itself among the input anagrams打印输入字谜中字谜和字谜单词本身的最大出现次数
【发布时间】:2020-09-25 18:23:26
【问题描述】:
a = ['ab', 'absa', 'sbaa', 'basa', 'ba']
res = []
s = 0
for i in range(len(a)):
    b=a[i]
    c = ''.join(sorted(b))
    res.append(c)
res.sort(reverse=False)
wordfreq = [res.count(p) for p in res]
d = dict(zip(res, wordfreq))
all_values = d.values()  #all_values is a list
max_value = max(all_values)
print(max_value)
max_key = max(d, key=d.get)
print(max_key)

在给定的问题中,用户输入各种字谜单词,输出应该是该单词的最大频率并打印这些字谜。 如果您能帮我从输入中打印出这些字谜,那将非常有帮助。

输出:

3 aabs       

预期输出:

3
absa sbaa basa

【问题讨论】:

    标签: python python-3.x anagram


    【解决方案1】:

    您可以创建一个单词字典 v/s 字谜列表

    然后打印出字谜列表中包含最多元素的单词

    from collections import defaultdict
    words = ['ab','absa','sbaa','basa','ba']
    wordToAnagram= defaultdict(list) 
    # word vs list anagram 
    # loop below will create {aabs:  ['absa', 'sbaa', 'basa']}
    for word in words:
        s = "".join(sorted(word))
        wordToAnagram[s].append(word)
    
    
    word, anagrams = max(wordToAnagram.items(), key=lambda x: len(x[1]))
    print(" ".join(anagrams))
    

    输出:

    3
    absa sbaa basa
    

    详情

    1. wordToAnagrams

    遍历单词后 wordToAnagram(dictionary) 是这样的

    {
    "ab" : ["ab", "ba"]
    "aabs":  ["absa",  "sbaa", "base"]
    }
    
    1. dictionary.items()

    wordToAnagram.items() 返回字典键值的元组对

    在哪里,

    key:是我们排序后的字符串"ab""aabs"

    value : 是字谜列表,例如 key = "ab",value 等于["ab", "ba"]

    dict_items([('ab', ['ab', 'ba']), ('aabs', ['absa', 'sbaa', 'base'])])
    
    1. max function using 'key' and lambda expression

    max(wordToAnagram.items(), key=lambda x: len(x[1]))

    通过比较 anagrams 列表 (len(x[1]) 的长度,从 wordToAnagram.items() 可迭代中找到最大值

    【讨论】:

    • 如果你解释一下这条线作为一个新手很难理解word, anagrams = max(wordToAnagram.items(), key=lambda x: len(x[1]))
    【解决方案2】:

    你可以试试numpymode 来自statistics 模块

    import numpy as np
    from statistics import mode
    
    words = ['ab','absa','sbaa','basa','ba']
    
    # This sorts the letters of each word, and creates a list of them
    sorted_words = [''.join(sorted(word)) for word in words]
    
    
    max_freq_anagrams = np.array(words)[np.array(sorted_words) == mode(sorted_words)]
    # mode(sorted_words) gives you the (sorted) word with the highest frequency
    # np.array(sorted_words) == mode(sorted_words) gives you a list of true/false 
    # and finaly you slice your words by this true/false list
    
    
    print(len(max_freq_anagrams))
    print(list(max_freq_anagrams))
    

    如果您有多个最大常​​用词,例如 words = ['ab','absa','sbaa','basa','ba', 'ba']

    然后使用max(set(sorted_words), key=sorted_words.count) 代替mode(sorted_words),它采用第一个最常用的词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 2016-06-02
      • 2011-02-07
      • 2015-10-31
      • 2011-10-29
      • 2019-03-05
      • 2013-03-19
      相关资源
      最近更新 更多