[Tutor] List comprehensions & matrix multiplication

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 24 May 2002 19:02:50 -0700 (PDT)


On Fri, 24 May 2002, dominic.fox wrote:

> After some playing around, I came up with the following as a way of
> doing matrix multiplications using the list comprehension syntax.
>
> def MatrixMultiply(first, second):
>     def sum(list):
>          def add(x, y): return x + y
>          return reduce(add, list)


This sum() function is useful enough that it might be good to pull it out
as an independent function.


I think doing nested list comprehensions might be overdoing things.  It's
a little hard for me to disentangle them mentally.



For variety, here's another version of matrix multiplication that enlists
the use of list comprehensions.  Dunno if it's "easier"  to understand,
since it's a different approach:

*** Spoiler space ahead ***










###
>>> def columnSlice(matrix, i):
...     return [row[i] for row in matrix]
...
>>> def rowSlice(matrix, i):
...     return matrix[i]
...
>>> def dot(vector1, vector2):
...     return sum([a * b for (a,b) in zip(vector1, vector2)])
...
>>> def MatrixMultiply(first, second):
...     result = [[0 for j in allCols(second)] for i in allRows(first)]
...     for i in allRows(first):
...         for j in allCols(second):
...             result[i][j] = dot(rowSlice(first, i),
...                                columnSlice(second, j))
...     return result
...
...
>>> MatrixMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]])
[[19, 22], [43, 50]]
>>> MatrixMultiply([[1, 2], [3, 4], [5, 6]], [[7], [8]])
[[23], [53], [83]]
###



Hope this helps!