This example shows three different ways of creating multiplication tables:
This version uses list comprehensions.
def mul1(n):
return array([[(i + 1) * (j + 1) for i in xrange(n)] for j in xrange(n)])
mul1(4)
array([[ 1, 2, 3, 4], [ 2, 4, 6, 8], [ 3, 6, 9, 12], [ 4, 8, 12, 16]])
timeit mul1(100)
100 loops, best of 3: 5.24 ms per loop
This version uses array manipulation and operations.
def mul2(n):
M = arange(1, n + 1).reshape((-1, 1))
M = tile(M, (1, n))
N = arange(1, n + 1).reshape((1, -1))
N = tile(N, (n, 1))
return M * N
mul2(4)
array([[ 1, 2, 3, 4], [ 2, 4, 6, 8], [ 3, 6, 9, 12], [ 4, 8, 12, 16]])
timeit mul2(100)
1000 loops, best of 3: 251 us per loop
Using NumPy is about 20 times faster here.
This version is an optimized version of the previous example, using broadcasting instead of unnecessary array tiling.
def mul3(n):
M = arange(1, n + 1).reshape((-1, 1))
N = arange(1, n + 1).reshape((1, -1))
return M * N
mul3(4)
array([[ 1, 2, 3, 4], [ 2, 4, 6, 8], [ 3, 6, 9, 12], [ 4, 8, 12, 16]])
timeit mul3(100)
10000 loops, best of 3: 88.3 us per loop
This optimized version is about 60 times faster than the original Python version.