Skip to content

Instantly share code, notes, and snippets.

@BlaiseRideout
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save BlaiseRideout/a05ed7b3538d623a1a6a to your computer and use it in GitHub Desktop.

Select an option

Save BlaiseRideout/a05ed7b3538d623a1a6a to your computer and use it in GitHub Desktop.
Two-Boolean matrix zeroer
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
def zeroify(matrix):
height = len(matrix)
width = len(matrix[0])
toZero = False
nextToZero = False
for col in range(0, width):
nextToZero |= 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):
toZero = nextToZero # the next row is now the current row
nextToZero = 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, check the next for zero
nextToZero |= matrix[row+1][col] == 0 # if the cell below the current cell contains a zero, then store that the next row does
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)
if toZero: # if this row contains zero
matrix[row][col] = 0 # zero the row
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