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...
thanks in advance

Recommended Answers

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:
Please use code tags to enclose your python code.

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
print numpy.add.reduce(v1*v2)  # 20

Numpy is a free high speed numeric extension module used by engineers and scientists.

thanks... =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.