-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanagram_path.py
65 lines (50 loc) · 1.7 KB
/
anagram_path.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import itertools
import pickle
import random
from collections import defaultdict, deque
from utils import NTHS, NUMS, WORDS
def anagram_sig(word):
return ''.join(sorted(word))
ANAGRAM_LOOKUP = defaultdict(list)
for word in WORDS:
ANAGRAM_LOOKUP[anagram_sig(word)].append(word)
class AnagramPath:
def __init__(self, message):
self.message = message
preprocess_path = 'anagram_path_preprocess/{}.pkl'.format(message.lower())
self.graph = pickle.load(
open(preprocess_path, 'rb'),
encoding='utf-8'
)
self.cur = None
self.mid = None
def generate(self, first_letter=None):
if self.cur is None:
if first_letter is None:
poss_starts = [(word, index) for word, index in self.graph if index == 0]
else:
poss_starts = [(word, index) for word, index in self.graph if index == 0 and first_letter in word]
self.cur = random.choice(poss_starts)
if self.mid is not None:
good_words = ANAGRAM_LOOKUP[self.mid]
elif self.cur is not None:
good_words = ANAGRAM_LOOKUP[self.cur[0]]
if first_letter is not None:
good_words = [word for word in good_words if word[0] == first_letter]
if not good_words:
return None
if self.mid is not None:
self.mid = None
else:
nxt = random.choice(list(self.graph[self.cur]))
# print "cur:", self.cur
# print "nxt:", nxt
# print "letter:", self.message[self.cur[1]]
self.mid = anagram_sig(self.cur[0] + nxt[0] + self.message[self.cur[1]])
# print "mid:", self.mid
self.cur = nxt
return random.choice(good_words)
def test():
generator = AnagramPath("FIRSTFIVE")
for _ in range(50):
print(generator.generate())