I need to calcualte the scalar product given two lists of numbers...

``````v1=input("Insert the first vector: ")
v2=input("Insert the second vector: ")

for i in range(len(v1)):
v3=v1[i]*v2[i]
print v3``````

this code will multiplie all the numbers in list v1 and the numbers in list v2 but the result doesn't come in a list...how can i make a list out of the results?how can i add all the numbers in a list?

i would apreciate if someone could help me...

All 5 Replies

You can code it like this ...

``````v1=input("Insert the first vector (eg, 1,2,3,4): ")
v2=input("Insert the second vector (eg. 4,3,2,1): ")
try:
v3 = []
for i in range(len(v1)):
v3.append(v1[i]*v2[i])
print v3
except IndexError:
print "vectors/lists need to be equal in length!"
``````

A note:

You probably know this, but just to be clear: the scalar product is the single number sum(v1*v2 for i in range(len(v1))).

Thus I would code:

``````def scalar_prod(v1,v2):
s = 0
for i in range(len(v1)):
s += v1[i]*v2[i]
return s``````

or even

``````def scalar_prod(v1,v2):
return sum([v1[i]*v2[i] for i in range(len(v1))])``````

Jeff

Or you could do this

``````import operator
a = (1,2,3,4)
b = (4,3,2,1)
print sum(map(operator.mul,a,b))``````

You can also use module numpy:

``````import numpy
v1 = numpy.array([1, 2, 3, 4])
v2 = numpy.array([4, 3, 2, 1])
# product
print v1*v2                    # [4 6 6 4]
# scalar product