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

Print the maximum occurence of the anagrams and the anagram words itself among the input anagrams

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)

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

O输出:

3 aabs       

预期输出:

3
absa sbaa basa

您可以创建单词词典 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() returns 字典键值元组对

其中,

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() 可迭代中找到最大值

你可以试试 numpy mode 来自 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),它采用第一个最常用的词。