You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
1.0 KiB
36 lines
1.0 KiB
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
|