Skip to content

Instantly share code, notes, and snippets.

@BlaiseRideout
Created August 4, 2015 17:40
Show Gist options
  • Select an option

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

Select an option

Save BlaiseRideout/306e884b7c5d53ebc1de to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import math
def zeroify(matrix):
height = len(matrix)
width = len(matrix[0])
p = primes(width + height)
a = 1
for row in range(0, height):
for col in range(0, width):
if matrix[row][col] == 0:
a *= p[col] * p[width + row]
for row in range(0, height):
for col in range(0, width):
if a % p[col] == 0 or a % p[width + row] == 0:
matrix[row][col] = 0
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 primes(n):
""" Returns a list of n primes """
return sieve(int(math.ceil(n*math.log(n*math.log(n)))))[0:n]
def sieve(n):
""" Returns a list of primes < n """
sieve = [True] * (n/2)
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i/2]:
sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1)
return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]
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