Python 打印输入字谜中字谜和字谜词本身的最大出现次数
在给定的问题中,用户输入各种字谜词,输出应该是该词的最大频率并打印这些字谜词。 如果你能帮我打印输入中的那些字谜,那将非常有帮助 输出:Python 打印输入字谜中字谜和字谜词本身的最大出现次数,python,python-3.x,anagram,Python,Python 3.x,Anagram,在给定的问题中,用户输入各种字谜词,输出应该是该词的最大频率并打印这些字谜词。 如果你能帮我打印输入中的那些字谜,那将非常有帮助 输出: 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
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
您可以创建一个单词词典v/s字谜列表 然后打印出字谜列表中包含最多元素的单词
3
absa sbaa basa
输出:
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))
详细信息
wordToAnagram(字典)
看起来像这样
3
absa sbaa basa
items()返回字典键值的元组对
在哪里,
键:我们的排序字符串是“ab”
还是“aabs”
值:是字谜的列表,例如对于key=“ab”,值等于[“ab”,“ba”]
max(wordToAnagram.items(),key=lambda x:len(x[1]))
通过比较字谜列表的长度(
len(x[1]
),从wordToAnagram.items()
iterable)中查找最大值。您可以尝试使用numpy
以及统计
模块中的模式
dict_items([('ab', ['ab', 'ba']), ('aabs', ['absa', 'sbaa', 'base'])])
如果您有多个最频繁的单词,例如。
words=['ab','absa','sbaa','basa','ba','ba']
然后使用
max(set(sorted\u words),key=sorted\u words.count)
代替mode(sorted\u words)
模式(sorted\u words)max(set(sorted\u words),key=lambda x:len(x[1])。
dict_items([('ab', ['ab', 'ba']), ('aabs', ['absa', 'sbaa', 'base'])])
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))