Last active
August 29, 2015 14:26
-
-
Save BlaiseRideout/317491d3e758017c3e0d to your computer and use it in GitHub Desktop.
One-Boolean matrix zeroer
This file contains hidden or 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
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| import random | |
| def zeroify(matrix): | |
| height = len(matrix) | |
| width = len(matrix[0]) | |
| toZero = False | |
| for col in range(0, width): | |
| toZero |= matrix[0][col] == 0 # check if any cells in the first row contain zero | |
| for row in range(1, height): | |
| if matrix[row][col] == 0: # if any columns contain zero | |
| matrix[0][col] = 0 # put them in the first row | |
| for row in range(0, height): | |
| if toZero: # if the current row contains a zero | |
| toZero = False # reset zero check for the next row | |
| for col in range(0, width): | |
| if row < (height - 1): # if we're not at the last row | |
| toZero |= matrix[row+1][col] == 0 # check if the next row contains zero | |
| if matrix[row][col] == 0: # if the current cell is zero | |
| matrix[row+1][col] = 0 # set the cell below it (handles zeroing columns down) | |
| matrix[row][col] = 0 # zero the row | |
| else: # if the current row doesn't contain zero, don't zero it | |
| for col in range(0, width): | |
| if row < (height - 1): # if we're not at the last row | |
| toZero |= matrix[row+1][col] == 0 # check if the next row contains zero | |
| if matrix[row][col] == 0: # if the current cell is zero | |
| matrix[row+1][col] = 0 # set the cell below it (handling zeroing columns down) | |
| return matrix | |
| def main(): | |
| mat = randomMatrix(random.randint(3,10), random.randint(3,10)) | |
| for i in range(0, 3): | |
| mat[random.randint(0, len(mat) - 1)][random.randint(0, len(mat[0]) - 1)] = 0 | |
| print "Initial matrix:" | |
| print prettify(mat) | |
| print "Zeroed matrix:" | |
| print prettify(zeroify(mat)) | |
| ## UTILITY FUNCTIONS ## | |
| def randomMatrix(width, height): | |
| matrix = [] | |
| for i in range(0, height): | |
| row = [] | |
| for j in range(0, width): | |
| row += [random.randint(0,255)] | |
| matrix += [row] | |
| return matrix | |
| def prettify(matrix): | |
| ret = u"┌ " + (" " * len(matrix[0]) * 4) + u"┐\n" | |
| for row in matrix: | |
| rowstr = u"│ " | |
| for elem in row: | |
| elemstr = str(elem) | |
| rowstr += elemstr + (" " * (4 - len(elemstr))) | |
| rowstr += u"│\n" | |
| ret += rowstr | |
| ret += u"└ " + (" " * len(matrix[0]) * 4) + u"┘" | |
| return ret | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment