Hi I'm following "Data Science from Scratch" and I got an error when I was making vector sum function. Could someone help?
The code:
a = [1,2,3]
b = [2,3,4]
def vector_add(v, w):
"""adds two vectors componentwise"""
return [v_i + w_i for v_i, w_i in zip(v,w)]
vector_add(a,b) #prints [3, 5, 7]
def vector_sum(vectors):
result = vectors[0]
for vector in vectors[1:]:
result = vector_add(result, vector)
return result
vector_sum(a)
Error:
TypeError Traceback (most recent call last)
<ipython-input-41-401c63999247> in <module>()
4 result = vector_add(result, vector)
5 return result
----> 6 vector_sum(a)
<ipython-input-41-401c63999247> in vector_sum(vectors)
2 result = vectors[0]
3 for vector in vectors[1:]:
----> 4 result = vector_add(result, vector)
5 return result
6 vector_sum(a)
<ipython-input-15-502c43cd9568> in vector_add(v, w)
4 def vector_add(v, w):
5 """adds two vectors componentwise"""
----> 6 return [v_i + w_i for v_i, w_i in zip(v,w)]
7 vector_add(a,b)
TypeError: zip argument #1 must support iteration
If you do
vector_sum(a)
the local variable result will be the integer "1" in your first step which is not iterable. So I guess you simply should call your functionvector_sum
liketo sum up multiple vectors. Latter gives
[4,7,10]
on my machine.If you want to sum up the components of one vector you should not use your
vector_add
function.