Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字母列表中查找所有可以生成的英语单词,每个字母的使用次数不超过列表中出现的次数_Python - Fatal编程技术网

Python 从字母列表中查找所有可以生成的英语单词,每个字母的使用次数不超过列表中出现的次数

Python 从字母列表中查找所有可以生成的英语单词,每个字母的使用次数不超过列表中出现的次数,python,Python,我试图将随机字母集输入函数,以便它返回文本文件中所有可能的单词,这些单词可以由这些随机字母组成,长度在4到9个字符之间。此时,代码返回仅由集合中的字母组成的单词,但在某些情况下,它会多次使用元素生成单词。我希望它只输出使用每个字母一次的单词。例如,“animal”将是return,但它已经使用了两次字母“a”来构成单词 letterList = ["a", "n", "i", "b", "s", "l", "s", "y", "m"] with open('american-english'

我试图将随机字母集输入函数,以便它返回文本文件中所有可能的单词,这些单词可以由这些随机字母组成,长度在4到9个字符之间。此时,代码返回仅由集合中的字母组成的单词,但在某些情况下,它会多次使用元素生成单词。我希望它只输出使用每个字母一次的单词。例如,“animal”将是return,但它已经使用了两次字母“a”来构成单词

letterList = ["a", "n", "i", "b", "s", "l", "s", "y", "m"] 

with open('american-english') as f:
    for w in f:
        w = w.strip()
        cond = all(i in letterList for i in w) and letterList[4] in w
        if 9 > len(w) >= 4 and cond:
            print(w)

一个简单的选择可能是使用现有方法比较每个字母的计数

您还可以尝试使用itertools.permutations从字母中生成所有可能的“单词”,并检查每个单词是否都在字典中。我怀疑这将是缓慢的,因为排列的数量将是巨大的,其中大多数不会是文字

查找字谜的常用方法是按字母顺序对两个单词的字母进行排序,然后进行相等比较:

sorted(word1)==sorted(word2)
如果这是真的,那么word1和word2就是字谜。您可以使用此方法减少比较次数,因为使用此技术,您只需要排序后唯一的排列

我已经编写了一个脚本来展示这三个功能,并允许您对它们进行基准测试。我的测试表明,随着字母列表变长,未经细化的itertools方法的伸缩性非常差。计数方法一般,但改进的itertools方法通常最快。当然,这些都可以进一步优化。跟他们一起去吧

import time
import itertools

letterList = list('catd')

#letter counting method
tic=time.time()
with open(r'D:/words_alpha.txt','r') as f:
    for word in f:
        if all([word.strip().count(letter) <= letterList.count(letter) for letter in word]):
            print(word.strip())
toc=time.time()
print(toc-tic)

#permutations with no refinement
tic=time.time()
with open(r'D:/words_alpha.txt','r') as f:
    for word in f:
        for n in range(1,len(letterList)+1):
            for pseudoword in itertools.permutations(letterList,n):
                if word.strip() == "".join(pseudoword):
                    print(word.strip())
toc=time.time()
print(toc-tic)

#permutations with anagram refinement
tic=time.time()
pwords=[]
for n in range(1, len(letterList) + 1):
    for pseudoword in itertools.permutations(letterList, n):
        if sorted(pseudoword) == list(pseudoword):
            pwords.append("".join(pseudoword))
print (pwords)
with open(r'D:/words_alpha.txt', 'r') as f:
    for word in f:
        if "".join(sorted(word.strip())) in pwords:
            print(word.strip())
toc=time.time()
print(toc-tic)
导入时间
进口itertools
字母列表=列表('catd')
#字母计数法
tic=time.time()
将open(r'D:/words_alpha.txt','r')作为f:
对于f中的单词:
如果全部([word.strip().count(字母))