打印输入的字谜中最大的出现字谜和字谜词本身

问题描述 投票:2回答:2
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
2个回答
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

详细信息

    wordToAnagrams
  • 反复遍历单词wordToAnagram(dictionary)看起来像这样

    { "ab" : ["ab", "ba"] "aabs": ["absa", "sbaa", "base"] }

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

    其中,

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

    值:是字谜列表,例如,对于键=“ ab”,值等于["ab", "ba"]

    dict_items([('ab', ['ab', 'ba']), ('aabs', ['absa', 'sbaa', 'base'])])

      max function using 'key' and lambda expression
  • max(wordToAnagram.items(), key=lambda x: len(x[1]))

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


  • 0
    投票
    您可以尝试使用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']

    然后用mode(sorted_words)代替max(set(sorted_words), key=sorted_words.count),它使用第一个最频繁出现的单词。

    © www.soinside.com 2019 - 2024. All rights reserved.