Skip to content

Commit b59435b

Browse files
solution for string rotation and zero matrix python
1 parent 88430c6 commit b59435b

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#!/usr/bin/python3
2+
import random
3+
4+
5+
def build_matrix(w, h, max=10):
6+
'''function that builds a matrix with random numbers including 0'''
7+
return [[random.randint(0, max) for _ in range(w)] for _ in range(h)]
8+
9+
10+
def zero_matrix(matrix):
11+
'''Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
12+
column are set to 0.'''
13+
row, column = [], []
14+
zero_present = False
15+
16+
for idx1 in range(len(matrix)):
17+
for idx2 in range(len(matrix[idx1])):
18+
if matrix[idx1][idx2] is 0:
19+
zero_present = True
20+
row.append(idx1)
21+
column.append(idx2)
22+
23+
if zero_present:
24+
for idx1 in range(len(matrix)):
25+
for idx2 in range(len(matrix[idx1])):
26+
if idx1 in row:
27+
matrix[idx1][idx2] = 0
28+
if idx2 in column:
29+
matrix[idx1][idx2] = 0
30+
31+
if __name__ == '__main__':
32+
matrix = build_matrix(4, 4)
33+
print("Old Matrix => ", matrix)
34+
zero_matrix(matrix)
35+
print("New Matrix => ", matrix)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/usr/bin/python3
2+
import unittest
3+
4+
def is_rotation(s1, s2):
5+
'''Assumeyou have a method isSubstringwhich checks if oneword is a substring
6+
of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one
7+
call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat"). '''
8+
if len(s1) is len(s2) and len(s1) > 0:
9+
return s2 in s1 + s1
10+
return False
11+
12+
13+
class Test(unittest.TestCase):
14+
def test1(self):
15+
self.assertTrue(is_rotation('waterbottle', 'erbottlewat'))
16+
self.assertFalse(is_rotation('watermellon', 'watermellons'))
17+
self.assertFalse(is_rotation('waterbottle', 'bottleaterw'))
18+
19+
20+
if __name__ == '__main__':
21+
unittest.main()

0 commit comments

Comments
 (0)