3 changed files with 44 additions and 29 deletions
-
36candidate_cache.py
-
1dictionary.py
-
36main.py
@ -0,0 +1,36 @@ |
|||||
|
import itertools |
||||
|
from dictionary import Dictionary, DICTS |
||||
|
|
||||
|
|
||||
|
def make_key(dictionary_name, letters): |
||||
|
return (dictionary_name, frozenset(letters)) |
||||
|
|
||||
|
|
||||
|
def candidates(letters, dictionary: Dictionary, min=2): |
||||
|
permutations = itertools.chain.from_iterable( |
||||
|
map(lambda r: itertools.permutations(letters, r), range(min, len(letters) + 1)) |
||||
|
) |
||||
|
return dictionary.filter(map("".join, permutations)) |
||||
|
|
||||
|
|
||||
|
class CandidateCache: |
||||
|
def __init__(self, maxsize=5): |
||||
|
self.maxsize = maxsize |
||||
|
self.cache = {} |
||||
|
self.keys = [] |
||||
|
|
||||
|
def get(self, dictionary_name, letters): |
||||
|
key = make_key(dictionary_name, letters) |
||||
|
try: |
||||
|
return self.cache[key] |
||||
|
except KeyError: |
||||
|
data = candidates(letters, DICTS[dictionary_name]) |
||||
|
self.create(key, data) |
||||
|
return data |
||||
|
|
||||
|
def create(self, key, data): |
||||
|
if len(self.keys) > self.maxsize: |
||||
|
key = self.keys.pop() |
||||
|
del self.cache[key] |
||||
|
self.keys.insert(0, key) |
||||
|
self.cache[key] = data |
||||
Write
Preview
Loading…
Cancel
Save
Reference in new issue