-
Notifications
You must be signed in to change notification settings - Fork 0
/
words.py
76 lines (52 loc) · 2.1 KB
/
words.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env python
import sys
from collections import Counter
scores = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4,
'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3,
'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8,
'y': 4, 'z': 10}
def word_score(word):
return sum(scores[char] for char in word)
def _word_find_comparator(word, letters):
letter_count = Counter(letters)
word_count = Counter(word)
for letter in word_count:
if letter not in letter_count or \
word_count[letter] > letter_count[letter]:
return False
return True
class ScrabbleCheater:
def __init__(self, path=None, words=None):
if words is None:
self.words = []
else:
self.words = words
if path is not None:
with open(path) as f:
for line in f.read().split("\n"):
if len(line) > 0:
self.words.append(unicode(line).lower())
def __repr__(self):
return repr(self.words)
def __search(self, search, comparator):
found = set()
search = search.lower()
for word in self.words:
if comparator(word, search):
found.add(word)
return sorted(found, key=word_score, reverse=True)
def find(self, letters):
found_words = self.__search(letters, _word_find_comparator)
return ScrabbleCheater(words=found_words)
def ends_with(self, suffix):
comparator = lambda word, ending: word.endswith(ending)
found_words = self.__search(suffix, comparator)
return ScrabbleCheater(words=found_words)
def starts_with(self, prefix):
comparator = lambda word, prefix: word.startswith(prefix)
found_words = self.__search(prefix, comparator)
return ScrabbleCheater(words=found_words)
def contains(self, substring):
comparator = lambda word, substring: substring in word
found_words = self.__search(substring, comparator)
return ScrabbleCheater(words=found_words)