Skip to content

Instantly share code, notes, and snippets.

@markpasc
Last active December 12, 2015 08:49
Show Gist options
  • Save markpasc/4747301 to your computer and use it in GitHub Desktop.
Save markpasc/4747301 to your computer and use it in GitHub Desktop.
regexp crossword solution checker
#!/usr/bin/env python
from itertools import izip, chain
import re
import sys
"""
Checks a solution to this regular expression crossword:
http://www.coinheist.com/rubik/a_regular_crossword/index.html
Image version: https://twitter.com/isaach/status/299595370760130561/photo/1
"""
left_clues = (
r'.*H.*H.*',
r'(DI|NS|TH|OM)*',
r'F.*[AO].*[AO].*',
r'(O|RHH|MM)*',
r'.*',
r'C*MC(CCC|MM)*',
r'[^C]*[^R]*III.*',
r'(...?)\1*',
r'([^X]|XCC)*',
r'(RR|HHH)*.?',
r'N.*X.X.X.*E',
r'R*D*M*',
r'.(C|HH)*',
)
top_clues = (
r'.*SE.*UE.*',
r'.*LR.*RL.*',
r'.*OXR.*',
r'([^EMC]|EM)*',
r'(HHX|[^HX])*',
r'.*PRR.*DDC.*',
r'.*',
r'[AM]*CM(RC)*R?',
r'([^MC]|MM|CC)*',
r'(E|CR|MN)*',
r'P+(..)\1.*',
r'[CHMNOR]*I[CHMNOR]*',
r'(ND|ET|IN)[^X]*',
)
bottom_clues = (
r'.*G.*V.*H.*',
r'[CR]*',
r'.*XEXM*',
r'.*DD.*CCM.*',
r'.*XHCR.*X.*',
r'.*(.)(.)(.)(.)\4\3\2\1.*',
r'.*(IN|SE|HI)',
r'[^C]*MMM[^C]*',
r'.*(.)C\1X\1.*',
r'[CEIMU]*OH[AEMOR]*',
r'(RX|[^R])*',
r'[^M]*M[^M]*',
r'(S|MM|HHH)*',
)
def match(pattern, text):
print "Checking %s against %s" % (text, pattern)
if re.match(r'^%s$' % pattern, text) is None:
print "Solution line %s doesn't match pattern %s" % (text, pattern)
sys.exit(0)
def check_left(solution):
for clue, text in izip(left_clues, solution):
match(clue, text)
def tilt_texts(solution):
square_grid = list()
for i in xrange(7):
square_grid.append("%-13s" % solution[i])
for i in xrange(7, 13):
square_grid.append("%13s" % solution[i])
for i in xrange(-1, -14, -1):
yield ''.join(row[i] for row in square_grid).strip()
def check_top(solution):
for clue, text in izip(top_clues, tilt_texts(solution)):
match(clue, text)
def check_bottom(solution):
bottom_texts = reversed(list(tilt_texts(list(reversed(solution)))))
for clue, text in izip(bottom_clues, bottom_texts):
match(clue, text)
def main():
print "Enter your solution row by row:"
solution = [x.strip().upper() for x in sys.stdin.readlines() if x.strip()]
check_left(solution)
check_top(solution)
check_bottom(solution)
print
print "All correct!"
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment