""" Alternative dictionary module for the keypad entry problem. Author: Rodney Topor Date: November 2007 """ import string # # initialise offsets of lower case letters (there must be a better way!) # offset = {} # n = 0 # for c in string.lowercase: # offset[c] = n # n = n + 1 # # mapping from letters to digits # digit = [ # '2', '2', '2', '3', '3', '3', # '4', '4', '4', '5', '5', '5', '6', '6', '6', # '7', '7', '7', '7', '8', '8', '8', '9', '9', '9', '9' # ] # # to map word to corresponding digit sequence: # digits = "".join([ digit[offset[c]] for c in word ]) # mapping from letters to digits alpha_to_digits = string.maketrans(string.lowercase, "22233344455566677778889999") # mapping from digit sequences to lists of words map = {} STARS = "************" def add_word(word): """Adds a word to the dictionary.""" # compute digit sequence corresponding to word digits = word.translate(alpha_to_digits) # add word to the list of words for this digit sequence if (map.has_key(digits)): map[digits].append(word) else: map[digits] = [word] def get_words(digits): """Returns the list of words associated with a digit sequence.""" if (map.has_key(digits)): words = map[digits] if (len(words) == 1): return words[0] else: return words return map[digits] else: return STARS[:len(digits)] def test(): add_word("foo") add_word("bar") print get_words('366') print get_words('227') test()