Find Possible Words That Can Be Made From 7 Random Letters
I'm trying to build a program in Python that, given a list of words and a list of letters, can determine what words can be made with 7 random letters from the list of letters. I ha
Solution 1:
Random.sample():
import random as rnd
letters = ['h','i','b', 'a','r','e', 'l', 'y', 'o', 'u', 'x', 'b']
hand = rnd.sample(letters, 7)
Then proceed as before.
Solution 2:
You can use Counter from collection to check for the ability to make each word out of the letters:
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']
Note: using Counter() covers the cases where the same letter is needed more than once (ex:baby).
Post a Comment for "Find Possible Words That Can Be Made From 7 Random Letters"