-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckpattern.py
64 lines (47 loc) · 1.62 KB
/
checkpattern.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
# "aabb" --> "cat cat dog dog" = true
# "aaba" -->"cat cat dog dog" = false
# "aaa" -->"dog cat cat" = false
# "abba" -->"cat dog dog cat" = true
# "bab" --> "cat dog cat" = true
# "123" --> "bat dog rat"
# "112" --> "bat bat rock"
# "112" --> "100 100 103"
# "1121" --> "100 100 103 100"
# abbacc
# pattern can be any letters, the string can be anything
#if follows the pattern, return return true, else return false
#if empty, return false
class Pattern():
def __init__(self, pattern, string):
self.pattern = pattern
self.string = string
self.patternLst = []
self.stringLst = []
def checkValid(self):
self.patternLst = list(self.pattern)
self.stringLst = self.string.split(" ")
if len(self.patternLst) != len(self.stringLst):
return False
return True
def checkPattern(self):
if not self.checkValid():
return False
else:
mapping = {}
p = self.patternLst
s = self.stringLst
for i in range(len(p)):
if p[i] not in mapping:
if s[i] in mapping.values():
return False
else:
mapping[p[i]] = s[i]
else:
if mapping[p[i]] == s[i]:
continue
else:
return False
return True
pattern1 = Pattern("aabc", "cat cat dog dog") #False
print(pattern1.checkValid()) #True
print(pattern1.checkPattern()) #False