Pagini recente » Cod sursa (job #3279241) | Cod sursa (job #1861116) | Cod sursa (job #978516) | Cod sursa (job #2641611) | Cod sursa (job #2650266)
import re
def get_lps(pat)->int:
i = 0
j = 1
lps = [0] * len(pat)
while j < len(pat):
if pat[i] == pat[j]:
lps[j] = i + 1
i += 1
j += 1
else:
if i != 0:
i = lps[i-1]
else:
lps[j] = 0
j += 1
return lps
def kmp(string, substring):
lps = get_lps(substring)
i, j = 0, 0
while i < len(string):
if string[i] == substring[j]:
i += 1
j += 1
if j == len(substring):
yield i - j
j = lps[j-1]
elif i < len(string) and string[i] != substring[j]:
if j != 0:
j = lps[j-1]
else:
i += 1
yield -1
with open('strmatch.in', 'r') as fin:
substring = fin.readline().rstrip('\n')
string = fin.readline().rstrip('\n')
pattern = re.compile(r'(?=({}))'.format(substring))
matches = tuple(re.finditer(pattern, string))
with open('strmatch.out', 'w') as fout:
fout.write(str(len(matches)) + '\n')
for x in matches[:1000]:
fout.write(str(x.span()[0]) + ' ')