This is what I have so far, but I’m stuck. I’m using nltk for the word list and trying to find all the words with the letters in “sand”. From this list I want to find all the words I can make from the remaining letters.
JavaScript
x
10
10
1
import nltk.corpus.words.words()
2
pwordlist = []
3
4
for w in wordlist:
5
if 's' in w:
6
if 'a' in w:
7
if 'n' in w:
8
if 'd' in w:
9
pwordlist.append(w)
10
In this case I have to use all the letters to find the words possible. I think this will work for finding the possible words with the remaining letters, but I can’t figure out how to remove only 1 instance of the letters in ‘sand’.
JavaScript
1
4
1
puzzle_letters = nltk.FreqDist(x)
2
3
[w for w in pwordlist if len(w) = len(pwordlist) and nltk.FreqDist(w) = puzzle_letters]
4
Advertisement
Answer
I would separate the logic into four sections:
- A function
contains(word, letters)
, which we’ll use to detect whether a word contains “sand” - A function
subtract(word, letters)
, which we’ll use to remove “sand” from the word. - A function
get_anagrams(word)
, which finds all of the anagrams of a word. - The main algorithm that combines all of the above to find words that are anagrams of other words once you remove “sand”.
JavaScript
1
25
25
1
from collections import Counter
2
3
words = ??? #todo: somehow get a list of every English word.
4
5
def contains(word, letters):
6
return not Counter(letters) - Counter(word)
7
8
def subtract(word, letters):
9
remaining = Counter(word) - Counter(letters)
10
return "".join(remaining.elements())
11
12
anagrams = {}
13
for word in words:
14
base = "".join(sorted(word))
15
anagrams.setdefault(base, []).append(word)
16
def get_anagrams(word):
17
return anagrams.get("".join(sorted(word)), [])
18
19
for word in words:
20
if contains(word, "sand"):
21
reduced_word = subtract(word, "sand")
22
matches = get_anagrams(reduced_word)
23
if matches:
24
print word, matches
25
Running the above code on the Words With Friends dictionary, I get a lot of results, including:
JavaScript
1
13
13
1
2
cowhands ['chow']
3
credentials ['reticle', 'tiercel']
4
cyanids ['icy']
5
daftness ['efts', 'fest', 'fets']
6
dahoons ['oho', 'ooh']
7
daikons ['koi']
8
daintiness ['seniti']
9
daintinesses ['sienites']
10
dalapons ['opal']
11
dalesman ['alme', 'lame', 'male', 'meal']
12
13