Liam_S - 1 year ago 492

Python Question

I'm fairly new to Python and trying to create a function to multiply a vector by a matrix (of any column size).

e.g.:

`multiply([1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]])`

[1, 1]

Here is my code:

`def multiply(v, G):`

result = []

total = 0

for i in range(len(G)):

r = G[i]

for j in range(len(v)):

total += r[j] * v[j]

result.append(total)

return result

The problem is that when I try to select the first row of each column in the matrix (r[j]) the error 'list index out of range' is shown. Is there any other way of completing the multiplication without using NumPy?

Answer Source

The length of your second `for`

loop is `len(v)`

and you attempt to indexing `v`

based on that so you got index Error . As a more pythonic way you can just use list comprehension and zip function :

```
>>> from operator import mul
>>> l,g=[1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]]
>>> z=zip(*g)
>>> [sum(mul(k,t) for k,t in i) for i in [zip(l,i) for i in z]]
[1, 1]
```

with `zip`

function you can get the columns of a list , so first you need to get the columns of list `g`

:

```
>>> zip(*g)
[(0, 1, 1, 1, 1, 0), (1, 1, 0, 0, 1, 1)]
```

then you need to zip this columns with list `l`

to calculate the multiple between those element :

```
>>> [zip(l,i) for i in z]
[[(1, 0), (0, 1), (0, 1), (1, 1), (0, 1), (0, 0)], [(1, 1), (0, 1), (0, 0), (1, 0), (0, 1), (0, 1)]]
```

at last all you need here is the sum of pairs mul that you can do it with `sum`

and `operator.mul`

:

```
sum(mul(k,t) for k,t in i)
```