-
Notifications
You must be signed in to change notification settings - Fork 2
/
pattern_match.py
111 lines (78 loc) · 2.34 KB
/
pattern_match.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# Wildcard string matching
# Given a string and a pattern, write a function to check whether the string matches the pattern. The pattern can contain '.' and '*', dot means matching any one character, star means matching zero to more characters.
def pattern_match(s,p):
if('*' not in p):
return matchdotonly(s, p)
isStar = (p[0] == "*")
si = 0
sj = 0
for pchunk in (p.split("*")):
# if there are multiple stars (*) continuously then just pass all except one
if(pchunk == ''):
isStar = True
sj += 1
continue
len_s_remaining = len(s[si:])
len_p_remaining = len(''.join(p.split("*")[sj+1:]))
if isStar:
matched = False
# replace star (*) with several number (0+) of dots (.) that represent any letter
while len_s_remaining - len_p_remaining - len(pchunk) >= 0:
if(matchdotonly(s[si:si+len(pchunk)], pchunk)):
matched = True
break
pchunk = '.' + pchunk
if(not matched):
return False
else:
if(not matchdotonly(s[si:si+len(pchunk)], pchunk)):
return False
si += len(pchunk)
sj += 1
isStar = True
return True
# compare string and pattern with "." symbol by symbol
def matchdotonly(s,p):
if(len(s) != len(p)):
return False
for k in range(len(s)):
if(k >= len(p)):
return False
if(s[k] == p[k] or p[k] == "."):
continue
else:
return False
return True
if __name__ == '__main__':
print "--- True tests ---"
s = 'abcdef'
p = 'abcdef'
print pattern_match(s, p)
s = 'abcdef'
p = 'a.c..f'
print pattern_match(s, p)
s = 'abcdef'
p = 'a*c*f'
print pattern_match(s, p)
s = 'abcdef'
p = 'a******f'
print pattern_match(s, p)
s = 'abcdef'
p = 'a**..**.**f'
print pattern_match(s, p)
print "--- False tests ---"
s = 'abcdef'
p = 'abcqdef'
print pattern_match(s, p)
s = 'abcdef'
p = 'a.e..f'
print pattern_match(s, p)
s = 'abcdef'
p = 'a*q*f'
print pattern_match(s, p)
s = 'abcdef'
p = 'a.....f'
print pattern_match(s, p)
s = 'abcdef'
p = 'a...f'
print pattern_match(s, p)