Skip to content

Instantly share code, notes, and snippets.

@oxc
Created June 29, 2020 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oxc/4f0b10aed09da7885307263fa0aaf71c to your computer and use it in GitHub Desktop.
Save oxc/4f0b10aed09da7885307263fa0aaf71c to your computer and use it in GitHub Desktop.
pattern.py
#!/usr/bin/env python
import sys
PATTERNS = [
("19,28 1 5","18,12 2 3","19,5 1 2","18,1 4 3","18,22 1 2","18,4 3 2","18,6 1 3"),
("19,2 4 1","18,1 4 3","19,5 1 2","19,12 1 3","19,6 11 1","18,22 1 2","18,15 1 2","19,12 1 3"),
("19,28 1 5","19,5 1 2","18,22 1 2","18,22 1 2","18,10 22 1","18,36 2 4","19,5 1 2","18,20 19 2"),
("19,5 1 2","18,20 19 2","19,6 11 1","18,1 4 3","18,10 22 1","18,20 19 2","18,1 3 1"),
("18,12 2 3","18,10 22 1","18,10 22 1","19,6 11 1","18,4 3 2","18,1 4 3"),
("18,4 8 1","18,4 3 2","18,22 1 2","19,1 3 6","18,6 1 3","18,12 2 3","18,15 1 2")
]
def match_word(word, pattern, mapping):
m = mapping
for p, c in zip(pattern, word):
if p in m:
if m[p] != c:
return None
else:
if m is mapping:
m = dict(mapping)
m[p] = c
return m
def match_all(candidates, patterns, mapping, matched_words, startword = None):
if len(patterns) == 0:
print(f"Success: {matched_words}")
return
p = patterns[0]
words = candidates[p]
for word in words:
if startword is not None:
if word == startword:
startword = None
else:
continue
if len(word) != len(p):
continue
print(f"Trying {matched_words}, {word}", end='\r', flush=True)
m = match_word(word, p, mapping)
if m is not None:
match_all(candidates, patterns[1:], m, matched_words + [word])
if __name__ == '__main__':
wordlist = sys.argv[1]
if len(sys.argv) > 2:
startword = sys.argv[2]
else:
startword = None
shortest = min(map(len, PATTERNS))
longest = max(map(len, PATTERNS))
words = []
for word in open(wordlist):
word = word.strip().lower()
if shortest <= len(word) <= longest:
words.append(word)
patcans = {}
for pattern in PATTERNS:
candidates = []
for word in words:
if match_word(word, pattern, {}) is not None:
candidates.append(word)
patcans[pattern] = candidates
print("Trying ...", flush=True)
match_all(patcans, PATTERNS, {}, [], startword)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment