-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathbfkmp.py
executable file
·57 lines (54 loc) · 1.68 KB
/
bfkmp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright 2010, 陈同 ([email protected]).
Please see the license file for legal information.
===========================================================
'''
__version__ = '0.1'
__revision__ = '0.1'
__author__ = 'chentong & ct586[9]'
__author_email__ = '[email protected]'
#=========================================================
def index(subseq, seq):
'''''
index(subseq, seq) -->a list of numbers or -1
Return an index of [subseq] in the [seq].
Or -1 if [subseq] is not a subsequence of [seq].
The time complexity of the algorithm is O(n*m), where
n, m = len(seq), len(subseq).
>>>index('12', '0112')
[2]
>>>index([1,2], [011212])
[2, 4]
>>>index('13', '0112')
-1
'''
i, n, m = -1, len(seq), len(subseq)
index = []
try:
while True:
i = seq.index(subseq[0], i+1, n - m + 1)
if subseq == seq[i:i+m]:
index.append(i)
except ValueError:
return index if len(index) > 0 else -1
def subseqInSeq(subseq, seq):
'''''
subseqInSeq(subseq, seq) ---> list or -1
The same as index.
'''
indexList = []
m = len(subseq)
subseqRepla = '*' * m
while subseq[0] in seq:
index = seq.index(subseq[0])
if subseq == seq[index:index+m]:
indexList.append(index)
seq = seq.replace(subseq, subseqRepla, 1)
else:
seq = seq.replace(subseq[0], '*', 1)
return (indexList if len(indexList) > 0 else -1)
def main():
print index('ab', 'abcdab')
print subseqInSeq('ab', 'abcdab')