Skip to content

Instantly share code, notes, and snippets.

@RafaelBroseghini
Created November 21, 2018 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RafaelBroseghini/a76d550c5fff33157d74476d044fdf8e to your computer and use it in GitHub Desktop.
Save RafaelBroseghini/a76d550c5fff33157d74476d044fdf8e to your computer and use it in GitHub Desktop.
Find the exact middle of a given matrix
"""
This program will find the element at the exact
middle of any columns (N) x rows (Y < N) matrix where
the number of columns and rows are odd.
# xxxxx | # xxxxx | # xxxx | # xxx
# xx(x)xx | # xxxxx | # xxxx | # x(x)x
# xxxxx | # No middle | # xxxx # No middle | # xxx
"""
def find_middle(matrix: list) -> int:
if len(matrix[0]) < len(matrix):
return -1
elif len(matrix[0]) % 2 == 0:
return -1
elif len(matrix[0]) % 2 == 1 and len(matrix) % 2 == 0:
return -1
return matrix[len(matrix)//2][len(matrix[0])//2]
if __name__ == "__main__":
assert find_middle([[1,2,3,4,5],[6,7,8,9,10],[0,0,0,0,0]]) == 8
assert find_middle([[1,2,3,4],[6,7,8,9],[0,0,0,0]]) == -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment