一個天真的做法是
import itertools
letters = ('','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz')
good_words = set(['wall','base','cats']) # etc
def allWords(s):
s = [int(ch) for ch in s.zfill(4)]
for word in itertools.product(letters[s[0]], letters[s[1]], letters[s[2]], letters[s[3]]):
word = ''.join(word)
if word in good_words:
yield word
words = list(allWords('2297'))
更有效的人會預處理所有的好詞到每個電話號碼列表的字典,只是做一個查詢:
import string
import collections
class CodingError(Exception):
pass
class TelephoneWords(object):
numbers = {
'a': '2', 'b': '2', 'c': '2', 'd': '3',
'e': '3', 'f': '3', 'g': '4', 'h': '4',
'i': '4', 'j': '5', 'k': '5', 'l': '5',
'm': '6', 'n': '6', 'o': '6', 'p': '7',
'q': '7', 'r': '7', 's': '7', 't': '8',
'u': '8', 'v': '8', 'w': '9', 'x': '9',
'y': '9', 'z': '9', '0': '0', '1': '1',
'2': '2', '3': '3', '4': '4', '5': '5',
'6': '6', '7': '7', '8': '8', '9': '9'
}
wordlen = 4
def __init__(self, wordlist=None, fname=None):
super(TelephoneWords,self).__init__()
self.words = collections.defaultdict(list)
if wordlist:
self.addwords(wordlist)
if fname:
with open(fname) as inf:
filestr = ' '.join(inf.readlines()).replace(string.punctuation, ' ')
self.addwords(filestr.split())
def addwords(self, words):
_wordlen = TelephoneWords.wordlen
_words = self.words
_encode = self.encode
for word in words:
if len(word)==_wordlen:
word = word.lower()
try:
_words[_encode(word)].append(word)
except CodingError:
pass
def addword(self, word):
self.addwords((word,))
def encode(self, s):
_numbers = TelephoneWords.numbers
res = []
for ch in s:
try:
res.append(_numbers[ch])
except KeyError:
# no corresponding value found
raise CodingError("No value available for char '{0}'".format(ch))
return ''.join(res)
def seek(self, num):
s = str(num).strip().zfill(TelephoneWords.wordlen)
try:
return self.words[s]
except KeyError:
raise ValueError("No words found for '{0}'".format(s))
def find(self, num, onErr=None):
try:
return self.seek(num)
except ValueError:
return [] if onErr is None else onErr
def main():
tw = TelephoneWords(fname='four_letter_words.txt')
for word in tw.find('2287'):
print word
if __name__=="__main__":
main()
使用拼字遊戲單詞列表,這給我
acts
bats
baur
cats
caup
這也有幫助。有很多我不知道你可以用這些語言來完成。也感謝這裏。 – 2011-03-23 01:45:37