Python:从7个随机字母中找出可能的单词

Python:从7个随机字母中找出可能的单词,python,Python,我正在尝试用Python构建一个程序,在给定一个单词列表和一个字母列表的情况下,可以确定哪些单词可以由字母列表中的7个随机字母组成 我有一个代码,显示列表中所有可能的单词,列表中的所有字母都有可能,但我需要将其更改为从列表中随机选择7个字母,然后查看列表中的哪些单词可以使用这些选定的字母生成 下面是使用所有字母的代码,并确定可以使用这些字母的单词: from collections import Counter words = ['hi','how','are','you'] letters

我正在尝试用Python构建一个程序,在给定一个单词列表和一个字母列表的情况下,可以确定哪些单词可以由字母列表中的7个随机字母组成

我有一个代码,显示列表中所有可能的单词,列表中的所有字母都有可能,但我需要将其更改为从列表中随机选择7个字母,然后查看列表中的哪些单词可以使用这些选定的字母生成

下面是使用所有字母的代码,并确定可以使用这些字母的单词:

from collections import Counter

words = ['hi','how','are','you']
letters = ['h','i','b', 'a','r','e', 'l', 'y', 'o', 'u', 'x', 'b'] 

# For every word
for word in words: 

    # Convert the word into a dictionary
    dict = Counter(word) 
    flag = 1

    # For every letter in that word
    for key in dict.keys():

        # If that letter is not in the list of available letters, set the flag to 0
        if key not in letters: 
            flag = 0

    # If the flag remains 1 (meaning all letters in the word are in the letters list), then print the word.
    if flag == 1:
        print(word)
现在,它正确地打印所有字母的可能单词,但我希望它从列表中随机选择7个字母,并打印可能的单词

感谢您的帮助。

Random.sample():

随机导入为rnd
字母=['h'、'i'、'b'、'a'、'r'、'e'、'l'、'y'、'o'、'u'、'x'、'b']
手=随机样本(字母,7)

然后像以前一样继续操作。

您可以使用collection中的计数器来检查从字母中提取每个单词的能力:

words   = ['hi','how','are','you']
letters = ['h','i','b', 'a','r','e', 'l', 'y', 'o', 'u', 'x', 'b']

from random      import sample
from collections import Counter

letterCounts  = Counter(sevenLetters)
wordCounts    = { word:Counter(word) for word in words }

sevenLetters  = sample(letters,7)
possibleWords = [ word for word,wc in wordCounts.items() if not wc-letterCounts ]

print(sevenLetters,possibleWords) 
# ['x', 'u', 'h', 'b', 'a', 'i', 'b'] ['hi']

注意:使用Counter()涵盖了多次需要同一个字母(例如:baby)的情况。

问题,列表中的
['h','a','p','y']
能否使单词
'happy'
?不,不能。它应该类似于拼字游戏。根据我的代码,它确实可以,尽管它不应该能够。我不知道怎么修复这个…你哪部分有问题?从列表中选择七个随机字母?是的,并且只在程序的其余部分使用这些数字。你不是说
rnd.sample
not
rnd.select
显然rnd.select()不是一件事-它说“模块随机没有属性选择”。啊,我用rnd.sample修复了它。谢谢你,杰克!这管用!有没有办法让它选择的字母包括“h”、“a”、“p”和“y”,那么“happy”这个词就不能拼写了?现在它忽略了字母列表中字母的编号是否正确。请参阅我对您的作品@RohanTaneja的评论!