Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ If you want to uninstall algorithms, it is as simple as:
- [spiral_traversal](algorithms/matrix/spiral_traversal.py)
- [crout_matrix_decomposition](algorithms/matrix/crout_matrix_decomposition.py)
- [cholesky_matrix_decomposition](algorithms/matrix/cholesky_matrix_decomposition.py)
- [sum_sub_squares](algorithms/matrix/sum_sub_squares.py)
- [queues](algorithms/queues)
- [max_sliding_window](algorithms/queues/max_sliding_window.py)
- [moving_average](algorithms/queues/moving_average.py)
Expand Down
24 changes: 24 additions & 0 deletions algorithms/matrix/sum_sub_squares.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Function to find sum of all
# sub-squares of size k x k in a given
# square matrix of size n x n
def sum_sub_squares(matrix, k):
n = len(matrix)
result = [[0 for i in range(k)] for j in range(k)]

if k > n:
return
for i in range(n - k + 1):
l = 0
for j in range(n - k + 1):
sum = 0

# Calculate and print sum of current sub-square
for p in range(i, k + i):
for q in range(j, k + j):
sum += matrix[p][q]

result[i][l] = sum
l += 1

return result

18 changes: 17 additions & 1 deletion tests/test_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
rotate_image,
sparse_dot_vector,
spiral_traversal,
sudoku_validator
sudoku_validator,
sum_sub_squares
)
import unittest

Expand Down Expand Up @@ -272,6 +273,21 @@ def test_sudoku_validator(self):
[3, 0, 0, 4, 8, 1, 1, 7, 9]
]))

class TestSumSubSquares(unittest.TestCase):
"""[summary]
Test for the file sum_sub_squares.py

Arguments:
unittest {[type]} -- [description]
"""
def test_sum_sub_squares(self):
mat = [[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5]]
self.assertEqual(sum_sub_squares.sum_sub_squares(mat, 3),
[[18, 18, 18], [27, 27, 27], [36, 36, 36]])

if __name__ == "__main__":
unittest.main()