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

  1. import itertools
  2. from dictionary import Dictionary, DICTS
  3. def make_key(dictionary_name, letters):
  4. return (dictionary_name, frozenset(letters))
  5. def candidates(letters, dictionary: Dictionary, min=2):
  6. permutations = itertools.chain.from_iterable(
  7. map(lambda r: itertools.permutations(letters, r), range(min, len(letters) + 1))
  8. )
  9. return dictionary.filter(map("".join, permutations))
  10. class CandidateCache:
  11. def __init__(self, maxsize=5):
  12. self.maxsize = maxsize
  13. self.cache = {}
  14. self.keys = []
  15. def get(self, dictionary_name, letters):
  16. key = make_key(dictionary_name, letters)
  17. try:
  18. return self.cache[key]
  19. except KeyError:
  20. data = candidates(letters, DICTS[dictionary_name])
  21. self.create(key, data)
  22. return data
  23. def create(self, key, data):
  24. if len(self.keys) > self.maxsize:
  25. key = self.keys.pop()
  26. del self.cache[key]
  27. self.keys.insert(0, key)
  28. self.cache[key] = data