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.
47 lines
1.3 KiB
47 lines
1.3 KiB
from collections import Counter
|
|
from dictionary import Dictionary, DICTS
|
|
|
|
|
|
def make_key(dictionary_name, letters):
|
|
return (dictionary_name, frozenset(Counter(letters).items()))
|
|
|
|
|
|
def candidates(letters, dictionary: Dictionary, min=2, permutations=None):
|
|
letter_counter = Counter(letters)
|
|
possibilities = []
|
|
for word in dictionary.word_frequency.keys():
|
|
word_counter = Counter(word)
|
|
try:
|
|
add = all(
|
|
word_counter[key] <= letter_counter[key] for key in word_counter.keys()
|
|
)
|
|
except KeyError:
|
|
add = False
|
|
if add:
|
|
possibilities.append(word)
|
|
return possibilities
|
|
|
|
|
|
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
|