google code jam exercise——Alien Language

进入Qualification Round 2009的试题,第一道题Alien Language,模式匹配的问题,既然选择了Python,可以使用Regular Expression正则表达式,那就是太简单了。

主要问题就在于把给定的pattern转换为regular expression,把"("和")"换成"["和"]"就可以了,代码如下:

#!/usr/bin/python
#
encoding:UTF-8
#
Filename:AlienLanguage.py

import sys
import re

inname = "input.txt"
outname = "output.txt"
if len(sys.argv)>1:
inname = sys.argv[1]
outname = inname.rstrip(".in")
outname = outname + ".out"
fin = open(inname,"r")
fout = open(outname,"w")

caseNum = 0

line = fin.readline()
ndata = [int(val) for val in line.split()]
letterNum = ndata[0]
testCaseNum = ndata[1]
patternNum = ndata[2]

caseData = []
for i in range(testCaseNum):
line = fin.readline()
line = line.rstrip("\n")
caseData.append(line)

patternData = []
for i in range(patternNum):
line = fin.readline()
line = line.rstrip("\n")
line = line.replace("(","[")
line = line.replace(")","]")
patternData.append(line)

for pattern in patternData:
caseNum = caseNum + 1
cnt = 0
for line in caseData:
if re.match(pattern,line):
cnt = cnt + 1
answer = "Case #%d: %d\n" %(caseNum,cnt)
fout.write(answer)

fin.close()
fout.close()

结果测试正确。
只是在测试large case的时候运行时间稍微有点长。

posted @ 2012-04-07 21:08  Frandy.CH  阅读(279)  评论(0编辑  收藏  举报