Last active
August 29, 2015 13:58
-
-
Save chrisguitarguy/10008198 to your computer and use it in GitHub Desktop.
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
#! /usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
""" | |
https://code.google.com/codejam/contest/90101/dashboard#s=p0 | |
""" | |
import re | |
import sys | |
PATTERN = re.compile(r'([a-z]|\([a-z]+\))') | |
def get_cases_and_words(fh): | |
""" | |
Read the headerline of the file - 3 integers separated by a space: | |
1. the length of a word in the alien language | |
2. the number of words in the language | |
3. the number of test cases | |
:return tuple: (testcases, wordlen, words) | |
""" | |
wordlen, wordcount, testcases = [int(x) for x in fh.readline().strip().split()] | |
words = list() | |
while len(words) < wordcount: | |
word = fh.readline().strip() | |
assert len(word) == wordlen | |
words.append(word) | |
assert len(words) == wordcount | |
return testcases, words | |
def match_letter(letters, words, idx): | |
return [w for w in words if w[idx] in letters] | |
def match_word(word, words): | |
""" | |
Find the possiblities for a word a word (whch is a list of tuples) | |
in a a given set of words. | |
""" | |
for i, letters in enumerate(word): | |
words = match_letter(letters, words, i) | |
if not words: | |
break | |
return words | |
def read_testcase(fh): | |
""" | |
Read a testcase line from the file handle tokenizing it into a list of | |
lists | |
:return list: | |
""" | |
line = fh.readline().strip() | |
match = PATTERN.findall(line) | |
if match is None: | |
raise ValueError('Unable to match {}'.format(line)) | |
return [tuple(x.strip('()')) for x in match] | |
def main(argv): | |
with open(argv[1]) as fh: | |
testcases, words = get_cases_and_words(fh) | |
for i in range(1, testcases+1): | |
line = read_testcase(fh) | |
possible = match_word(line, words) | |
print('Case #{case}: {poss}'.format(case=i, poss=len(possible))) | |
return 0 | |
if __name__ == "__main__": | |
try: | |
sys.exit(main(sys.argv)) | |
except IndexError: | |
print("Usage: {} [inputfile]".format(sys.argv[0]), file=sys.stderr) | |
sys.exit(1) | |
except Exception as ex: | |
print("Uncaught {e} exception: {msg}".format(e=ex.__class__.__name__, msg=str(ex))) | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment