Skip to content

Commit dd30832

Browse files
python: add problem 59 and unittest
1 parent dcfd6aa commit dd30832

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

Python/sln_1_100/solution_51_60.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from itertools import permutations
33
from common_utils import Interval
44

5+
56
class Solution_51_60:
67
def solveNQueens(self, n):
78
"""
@@ -60,6 +61,7 @@ def spiralOrder(self, matrix):
6061
curr_direction = (curr_direction + 1) % 4
6162

6263
return res
64+
6365
def merge(self, intervals):
6466
"""
6567
56
@@ -80,6 +82,7 @@ def merge(self, intervals):
8082
new_intervals.append(Interval(start, end))
8183
last_start, last_end = start, end
8284
return new_intervals
85+
8386
def lengthOfLastWord(self, s):
8487
"""
8588
58
@@ -106,3 +109,29 @@ def lengthOfLastWord(self, s):
106109
last_ch = cur_ch
107110
index -= 1
108111
return end - start
112+
113+
def generateMatrix(self, n):
114+
"""
115+
59
116+
:param n:
117+
:return:
118+
"""
119+
x, y = 0, -1
120+
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
121+
steps = [n, n - 1]
122+
123+
val = 1
124+
matrix = [[0] * n for _ in range(n)]
125+
direction_index = 0
126+
127+
while steps[direction_index % 2]:
128+
curr_direction = directions[direction_index]
129+
for _ in range(steps[direction_index % 2]):
130+
x += curr_direction[0]
131+
y += curr_direction[1]
132+
matrix[x][y] = val
133+
val += 1
134+
steps[direction_index % 2] -= 1
135+
direction_index = (direction_index + 1) % 4
136+
137+
return matrix

Python/sln_1_100/test_solution_51_60.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from sln_1_100.solution_51_60 import Solution_51_60
33
from common_utils import Interval
44

5+
56
# -*- coding: UTF-8 -*-
67
class TestSolution_51_60(TestCase):
78
def setUp(self):
@@ -12,12 +13,17 @@ def test_spiralOrder(self):
1213
res = [1, 2, 3, 6, 9, 8, 7, 4, 5]
1314
self.assertEqual(self.sln.spiralOrder(m), res)
1415
self.assertEqual(self.sln.spiralOrder([[1]]), [1])
16+
1517
def test_merge(self):
16-
raw_span1 = [[1,3],[2,6],[8,10],[15,18]]
17-
span1 = [Interval(start,end) for start,end in raw_span1]
18+
raw_span1 = [[1, 3], [2, 6], [8, 10], [15, 18]]
19+
span1 = [Interval(start, end) for start, end in raw_span1]
1820

1921
def test_lengthOfLastWord(self):
2022
length = self.sln.lengthOfLastWord('Hello world')
2123
self.assertEqual(length, 5)
2224
self.assertEqual(self.sln.lengthOfLastWord(' '), 0)
2325
self.assertEqual(self.sln.lengthOfLastWord('a '), 1)
26+
27+
def test_generateMatrix(self):
28+
matrix = self.sln.generateMatrix(3)
29+
self.assertEqual(matrix, [[1, 2, 3], [8, 9, 4], [7, 6, 5]])

0 commit comments

Comments
 (0)