-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatternMatcher.py
More file actions
31 lines (29 loc) · 1.01 KB
/
Copy pathpatternMatcher.py
File metadata and controls
31 lines (29 loc) · 1.01 KB
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
"""
Returns whether the given string can be represented by the pattern sequence.
string - GraphGraphGraph
pattern - aaa
"""
def findPattern(string, pattern):
mappings = {}
return helper(string, 0, pattern, 0, mappings)
def helper(string, index, pattern, pos, mappings):
if pos == len(pattern) and index == len(string):
return True
elif pos == len(pattern) or index == len(string):
return False
if pattern[pos] in mappings:
val = mappings[pattern[pos]]
if len(val) + index > len(string) or string[index:index+len(val)] != val:
return False
return helper(string, index + len(val), pattern, pos + 1, mappings)
for a in range(len(string)):
mappings[pattern[pos]] = string[index:index+a+1]
if helper(string, index+a+1, pattern, pos+1, mappings):
return True
del mappings[pattern[pos]]
return False
# Testing - Should print True, False, True, True
print(findPattern("GraphGraphGraph", "aaa"))
print(findPattern("hey", "aa"))
print(findPattern("OhMyGod", "abc"))
print(findPattern("OhMyOhOhHey", "abaac"))