forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add sum of sub squares of a given nxn matrix (keon#631)
* Added function to calculate sum of all sub-squares in a square matrix * Added test for sum_sub_squares function * Updated README
- Loading branch information
siderism
authored
Feb 13, 2020
1 parent
38173ae
commit ebc8de4
Showing
3 changed files
with
42 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters