Back to home

Test fileSpiral MatrixRunning tests
Python Spiral Matrix main image

Python Spiral Matrix

Test file

Create file spiral_matrix_test.py:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import unittest import spiral_matrix class GeneralMatrixTest(unittest.TestCase): def test_matrices(self): asserts = [ { "input": 3, "expected": [[1, 2, 3], [8, 9, 4], [7, 6, 5]] } ] for test in asserts: res = spiral_matrix.create(test["input"]) self.assertEqual(res, test["expected"]) if __name__ == '__main__': unittest.main()

Spiral Matrix

Create file spiral_matrix.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 def create(dim): """ Create a matrix of size n. dim: integer defining n x n matrix. """ mat = [] i = 0 j = 0 while i < dim: mat.append([]) while j < dim: j = j + 1 mat[i].append(0) i = i + 1 j = 0 count = 1 startCol = 0 endCol = dim - 1 startRow = 0 endRow = dim - 1 while startCol <= endCol and startRow <= endRow: # startRow i = startCol while i <= endCol: mat[startRow][i] = count count = count + 1 i = i + 1 startRow = startRow + 1 # endCol i = startRow while i <= endRow: mat[i][endCol] = count count = count + 1 i = i + 1 endCol = endCol - 1 # endRow i = endCol while i >= startCol: mat[endRow][i] = count count = count + 1 i = i - 1 endRow = endRow - 1 # startCol i = endRow while i >= startRow: mat[i][startCol] = count count = count + 1 i = i - 1 startCol = startCol + 1 return mat

Running tests

Change into directory and run python3 -m pytest -v spiral_matrix_test.py.

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.