-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanagrammer.py
57 lines (46 loc) · 1.58 KB
/
anagrammer.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
import logging
import shelve
class Anagrammer(object):
""" Anagram database
Attributes:
db: opened anagram database
"""
def __init__(self, anagram_database):
try:
self.db = shelve.open(anagram_database, "r")
except IOError:
logging.exception("Failed to open anagram database")
self.db = None
logging.debug("Opened anagram database successfully")
def __look_up(self, word):
""" Perform a lookup on a set of characters. Internal method.
:param str word: letters to use in lookup
:return: Valid anagrams
:rtype: list[str]
"""
lookup = "".join(sorted(word)) # Sort for hashing, essentially
if lookup in self.db:
return self.db[lookup]
else:
return []
def get_anagrams(self, letters):
""" Return valid anagrams of letters. Don't include the strint that
was passed in.
:param str letters: Letters to be anagrammed
:return: List of valid anagrams
:rtype: list[str]
"""
logging.debug("Looking up in anagram db: " + letters)
results = self.__look_up(letters)
# don't return the letters themselves
if letters in results:
results.remove(letters)
return results
def is_word(self, word):
""" Check if word is present in our anagram dictionary
:param str word:
:return: True if present in anagram dictionary
:rtype: bool
"""
results = self.__look_up(word)
return word in results