Last active
August 22, 2019 12:16
-
-
Save tburette/8c9064bb2b7c9c1d45d1911aba54053d to your computer and use it in GitHub Desktop.
Regex Crossword character class solver helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Helps solving https://regexcrossword.com/ that use character classes.""" | |
def letters(string): | |
"""Converts a string representing a character class into the set of letters that can match it. | |
Args: | |
string (str): String representing a Character class. Can be '^A-CX-Z' or '[^A-CX-Z]' | |
Returns: | |
set: A set of (upper case) letters matching the character class | |
""" | |
string = string.upper() | |
def pop_left(): | |
nonlocal string | |
first, *string = string | |
return first | |
def letters_set(a, b): | |
return set(''.join([chr(x) for x in range(ord(a), ord(b)+1)])) | |
if string[0] == '[': | |
pop_left() | |
if string[0] == '^': | |
reverse = True | |
pop_left() | |
else: | |
reverse = False | |
result = set() | |
while string: | |
start = pop_left() | |
if start == ']': | |
continue | |
if string[0] == '-': | |
pop_left() | |
end = pop_left() | |
result = result | letters_set(start, end) | |
if reverse: | |
result = letters_set('A', 'Z') - result | |
return result | |
# https://regexcrossword.com/challenges/doublecross/puzzles/1 | |
# v = vertical | |
# h = horizontal | |
# l = left | |
# r = right | |
v1t = letters('[D-HJ-M]') | |
v1b = letters('[^F-KM-Z]') | |
v2t = letters('[^A-RU-Z]') | |
v2b = letters('[A-KS-V]') | |
h1l = letters('[A-GN-Z]') | |
h1r = letters('[^A-DI-S]') | |
print(v1t & v1b & h1l & h1r) | |
print(v2t & v2b & h1r & h1r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment