Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
The first rule of numpy is NO CYCLES!
from time import time
import numpy
from numpy.lib.stride_tricks import as_strided
def fill_matrix_python(width, height):
i, j = numpy.mgrid[0:height, 0:width]
return 22. / (i + j + 2)
def fill_matrix_native(width, height):
array = numpy.arange(2, width + height + 2)
stride = array.strides[0]
view_2d = as_strided(array,
shape=(width, height),
strides=(stride, stride))
return 22. / view_2d
start_time = time()
fill_matrix_python(10000, 10000)
print('Python implementation: Matrix 10000x10000 filled in %.3f seconds' % (time() - start_time))
start_time = time()
fill_matrix_native(10000, 10000)
print('Native implementation: Matrix 10000x10000 filled in %.3f seconds' % (time() - start_time))
Python implementation: Matrix 10000x10000 filled in 3.332 seconds
Native implementation: Matrix 10000x10000 filled in 0.532 seconds
def fill(c, width, height):
for i in range(height):
for j in range(width):
c[i][j] = round(22/(i+j+2), 1)
return c
a = [[0]*5 for _ in range(5)]
for i in fill(a, 5, 5):
print(i)
without numpy something like this
def create_matrix(h, w):
a = []
for i in range(h):
a.append([])
for j in range(w):
a[i].append(22/(i+j+2))
return a
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question