Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 661d3c0

Browse files
python: add problem 74 and unittest
1 parent dc223c9 commit 661d3c0

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

Python/sln_1_100/solution_71_80.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
class Solution_71_80(object):
88
def simplifyPath(self, path):
99
"""
10+
71
1011
:type path: str
1112
:rtype: str
1213
"""
@@ -37,6 +38,49 @@ def simplifyPath(self, path):
3738

3839
return '/' + '/'.join(final_path_segments)
3940

41+
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
42+
"""
43+
74
44+
:param matrix:
45+
:param target:
46+
:return:
47+
"""
48+
if not matrix:
49+
return False
50+
if not matrix[0]:
51+
return False
52+
row = len(matrix) - 1
53+
col = len(matrix[0]) - 1
54+
55+
def binary_search(func, l):
56+
left = 0
57+
right = l
58+
if func(0) >= target:
59+
return 0
60+
elif func(l) <= target:
61+
return l
62+
else:
63+
mid = (left + right) // 2
64+
while left < mid:
65+
mid_val = func(mid)
66+
if mid_val < target:
67+
left = mid
68+
elif mid_val > target:
69+
right = mid
70+
else:
71+
return mid
72+
mid = (left + right) // 2
73+
74+
return left
75+
76+
row_index = binary_search(lambda i: matrix[i][0], row)
77+
if matrix[row_index][0] == target:
78+
return True
79+
col_index = binary_search(lambda i: matrix[row_index][i], col)
80+
if matrix[row_index][col_index] == target:
81+
return True
82+
return False
83+
4084
def combine(self, n: int, k: int) -> List[List[int]]:
4185
"""
4286
77

Python/sln_1_100/test_solution_71_80.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,24 @@ def test_simplifyPath(self):
1515
self.assertEqual(self.sln.simplifyPath('///'), '/')
1616
self.assertEqual(self.sln.simplifyPath('/...'), '/...')
1717

18+
def test_search_martrix(self):
19+
matrix = [
20+
[1, 3, 5, 7],
21+
[10, 11, 16, 20],
22+
[23, 30, 34, 50]
23+
]
24+
self.assertEqual(self.sln.searchMatrix(matrix, 3), True)
25+
self.assertEqual(self.sln.searchMatrix(matrix, 7), True)
26+
self.assertEqual(self.sln.searchMatrix(matrix, 11), True)
27+
self.assertEqual(self.sln.searchMatrix(matrix, 50), True)
28+
self.assertEqual(self.sln.searchMatrix(matrix, 8), False)
29+
self.assertEqual(self.sln.searchMatrix(matrix, 100), False)
30+
self.assertEqual(self.sln.searchMatrix(matrix, 23), True)
31+
self.assertEqual(self.sln.searchMatrix(matrix, 0), False)
32+
self.assertEqual(self.sln.searchMatrix(matrix, 1), True)
33+
self.assertEqual(self.sln.searchMatrix([], 1), False)
34+
self.assertEqual(self.sln.searchMatrix([[]], 1), False)
35+
1836
def test_combine(self):
1937
ret = self.sln.combine(4, 2)
2038
self.assertEqual(ret, [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]])

0 commit comments

Comments
 (0)