1+ ########
2+ # Code #
3+ ########
4+
5+ # pattern and matrix are both 2D arrays
6+ # return true as soon as the pattern is found for a first time
7+ def patternInMatrix (pattern , matrix ):
8+ rows , cols = len (matrix ), len (matrix [0 ])
9+ patternRows , patternCols = len (pattern ), len (pattern [0 ])
10+ for row in xrange (rows - patternRows ):
11+ for col in xrange (cols - patternCols ):
12+ found = False
13+ for pRow in xrange (patternRows ):
14+ for pCol in xrange (patternCols ):
15+ if pattern [pRow ][pCol ] != matrix [row + pRow ][col + pCol ]:
16+ found = False
17+ break
18+ else :
19+ found = True
20+ if found :
21+ return True
22+ return False
23+
24+ # return a list of all top-left starting indices
25+ def indicesOfPatternInMatrix (pattern , matrix ):
26+ rows , cols = len (matrix ), len (matrix [0 ])
27+ patternRows , patternCols = len (pattern ), len (pattern [0 ])
28+
29+ startingSpots = []
30+ for row in xrange (rows - patternRows + 1 ):
31+ for col in xrange (cols - patternCols + 1 ):
32+ found = False
33+ for pRow in xrange (patternRows ):
34+ for pCol in xrange (patternCols ):
35+ if pattern [pRow ][pCol ] != matrix [row + pRow ][col + pCol ]:
36+ found = False
37+ break
38+ else :
39+ found = True
40+ if found :
41+ startingSpots .append ((row , col ))
42+ return startingSpots
43+
44+ #########
45+ # Tests #
46+ #########
47+
48+ def testPatterInMatrix ():
49+ assert patternInMatrix ([[1 ]], [[0 ,0 ,0 ],[0 ,1 ,0 ],[0 ,0 ,0 ]])
50+ assert not patternInMatrix ([[2 ]], [[0 ,0 ,0 ],[0 ,1 ,0 ],[0 ,0 ,0 ]])
51+
52+ def testIndicesOfPatternInMatrix ():
53+ p0 = [[1 ]]
54+
55+ m0 = [[0 ,0 ,0 ],
56+ [0 ,1 ,0 ],
57+ [0 ,0 ,0 ]]
58+ assert indicesOfPatternInMatrix (p0 , m0 ) == [(1 , 1 )]
59+
60+ p1 = [[2 ]]
61+
62+ m1 = [[0 ,0 ,0 ],
63+ [0 ,1 ,0 ],
64+ [0 ,0 ,0 ]]
65+ assert indicesOfPatternInMatrix (p1 , m1 ) == []
66+
67+ p2 = [[0 ,1 ,0 ]]
68+
69+ m2 = [[0 ,0 ,0 ],
70+ [0 ,1 ,0 ],
71+ [0 ,0 ,0 ]]
72+ assert indicesOfPatternInMatrix (p2 , m2 ) == [(1 , 0 )]
73+
74+ p3 = [[0 ,0 ,0 ],
75+ [0 ,1 ,0 ],
76+ [0 ,0 ,0 ]]
77+
78+ m3 = [[0 ,0 ,0 ],
79+ [0 ,1 ,0 ],
80+ [0 ,0 ,0 ]]
81+ assert indicesOfPatternInMatrix (p3 , m3 ) == [(0 ,0 )]
82+
83+ p4 = [[0 ]]
84+
85+ m4 = [[0 ,0 ,0 ],
86+ [0 ,1 ,0 ],
87+ [0 ,0 ,0 ]]
88+ assert indicesOfPatternInMatrix (p4 , m4 ) == [(0 ,0 ),(0 ,1 ),(0 ,2 ),
89+ (1 ,0 ),(1 ,2 ),
90+ (2 ,0 ),(2 ,1 ),(2 ,2 )]
91+
92+ p4 = [[0 , 0 ]]
93+
94+ m4 = [[0 ,0 ,0 ],
95+ [0 ,1 ,0 ],
96+ [0 ,0 ,0 ]]
97+ assert indicesOfPatternInMatrix (p4 , m4 ) == [(0 ,0 ),(0 ,1 ),
98+ (2 ,0 ),(2 ,1 )]
99+
100+ def main ():
101+ testPatterInMatrix ()
102+ testIndicesOfPatternInMatrix ()
103+
104+ if __name__ == "__main__" :
105+ main ()
0 commit comments