Giving the following example list the task is: find out whether the second expression is in the first one.
*
shall be considered as a wildcard for any character and one should be able to escape it\*
Hello,ell This is good, is CodeEval,C*Eval Old,Young
should evaluate to
true true true false
I wrote the following code which solves this problem. However, my solution seems very cumbersome and slow. Do you know how to improve it? (The task is for CodeEval and this solution is actually too slow. The actual solution which succeeded is much shorter but it does not check if the search_exprs
are in the right order)
import sys
import re
def all_occ(ss, s):
""" Finds All Occurences of substring ss in string s and returns
for each occurence its last index
"""
start = 0
while True:
try:
start = s.index(ss,start)+len(ss)
except ValueError:
break
yield start
def is_ss(s, ss):
search_exprs = [x.replace('\*', '*') for x in re.split(r'(?<!\\)\*', ss)]
# Get the list of all occurences of each search expression
find_indices = [list(all_occ(sub, s)) for sub in search_exprs]
# If any of the indices is not found, then the expression does not match
if not any(find_indices):
return "false"
# Check if the expressions are in the right order
start = 0
for el in find_indices:
start = min([e for e in el if e>start])
if not start:
return "false"
return "true"
for line in open(sys.argv[1]).read().splitlines():
if line:
print is_ss(*line.split(','))
EDIT: Just fyi: here the actual solution that has been accepted by codeeval but would fail if the expressions were in the wrong ordere:
import sys
import re
def is_ss(s, ss):
search_exprs = [x.replace('\*', '*') for x in re.split(r'(?<!\\)\*', ss)]
if any(map(lambda x: x in s, search_exprs)):
return "true"
else:
return "false"
for line in open(sys.argv[1]).read().splitlines():
if line:
print is_ss(*line.split(','))