-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind.py
70 lines (61 loc) · 1.78 KB
/
find.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
"""
Simple scrabble word finder
Given a pattern like __i, and a
scrabble tray, finds matching
words in the wordlist
"""
import sys # to get pattern from argv
import letterbag
import re # (added after class ... regular expression package)
def search(f, pattern, tray):
results = [ ]
pattern = fixpat(pattern)
dfa = re.compile(pattern)
for word in f:
word = word.strip()
if matches(word, dfa, pattern, tray):
results.append(word)
return results
def matches(word, dfa, pattern, tray):
"""
Word matches pattern with tray.
Returns True if the word can be made from the
letters in the tray and pattern, and if it also
matches the pattern (see matchpat).
"""
return matchpat(word, dfa) and made_from(word, pattern+tray)
def made_from(word, letters):
bag = letterbag.LetterBag(letters)
return bag.contains(word)
def matchpat(word, dfa):
"""
A letter x matches that letter.
FIXME now uses regular expressions
- (hyphen) matches any letter
_ (underscore) matches any sequence of letters
if X matches A, and Y matches B, then
XY matches AB.
For example '_ch-s' matches 'branches' but not 'branchings'
"""
return dfa.fullmatch(word)
def fixpat(pattern):
pat = re.sub("_", ".+", pattern)
pat = re.sub("-", ".", pat)
return pat
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python3 find.py _ch-p_ aebxyqrz'")
exit(0)
words = open("dict.txt")
pattern = sys.argv[1]
tray = sys.argv[2]
result = search(words, pattern, tray)
on_line = 0
for w in result:
if on_line >= 4:
print()
on_line = 0
print(w, end="\t")
on_line += 1
print()
print("{} matches".format(len(result)))