Reputation: 73
I have this task to do the dot product of two vectors in the form of lists. I tried this method but it gives me the wrong answer, not quite sure what the issue is.
def scalar_product(vec1,vec2):
new_list = []
a_zip = zip(vec1, vec2)
result = 1
zipped_list = list(a_zip)
for lists in zipped_list:
for integer in lists:
result = result * integer
new_list.append(result)
return sum(new_list)
print(scalar_product([1,1,1],[2,2,2]))
So my thought process here was to first zip
the lists together so I get one big list containing sublists. Then I looped through the lists and the sublist to multiply the values in the sub-lists and append that to a new_list
. And then to sum up the new_list
. But the output here is 21 when it actually should be 6.
I don't want to import
any modules or such for this.
Upvotes: 1
Views: 916
Reputation: 2443
def scalar_product(vec1,vec2):
total_sum = 0
for x, y in zip(vec1, vec2):
total_sum = total_sum + (x*y)
return total_sum
print(scalar_product([1,1,1],[2,2,2]))
# 6
Here is what each step is doing.
Take the example: vec1 = [1,2,3]
, vec2=[5,6,7]
zip(vec1,vec2) # is an iterator with value [(1,5),(2,6),(3,7)]
total_sum = 0 # the total sum is currently initialized to zero.
for x,y in zip(vec1,vec2) # assigns x and y from the zipped iterator.
# On the first round x = 1, y = 5
# On the second round x = 2, y = 6
# On the final round x = 3, y = 7
total_sum = total_sum + (x*y)
# On the first round total_sum = 0 + 1*5 = 5
# On the second round total_sum = 5 + 2*6 = 17
# On the final round total_sum = 17 + 3*7 = 38
return tota_sum # total_sum is now 38.
Upvotes: 2
Reputation: 11
There are many ways to make obtain the answer, one that is easy to read is as follows: (it iterates number of times equal to the length of the vectors and sum the multiplications)
def scalar_product(vec1,vec2):
sum=0
for count in range(0,len(vec1)): # could be len(vec2), it doesn't matter
sum=sum+vec1[count]*vec2[count]
return sum
print(scalar_product([1,1,1],[2,2,2]))
Upvotes: 1
Reputation: 531693
def scalar_product(vec1, vec2):
return sum(map(lambda x, y: x*y, vec1, vec2))
A trivial import from the standard library makes this simpler:
from operator import mul
def scalar_product(vec1, vec2):
return sum(map(mul, vec1, vec2))
If you are really averse to an import, and you know the type of value in the vectors, you can hard-code an unbound method instead. (But really, just use the trivial import.) For example,
def scalar_product(vec1, vec2):
return sum(map(float.__mul__, vec1, vec2))
You can also use a generator expression in place of map
:
def scalar_product(vec1, vec2):
return sum(x*y for x, y in zip(vec1, vec2))
Upvotes: 2
Reputation: 1486
you can try this one liner
a,b= [1,1,1],[2,2,2]
c= sum([(lambda x,y: x*y)(x,y)for x,y in zip(a,b)])
Upvotes: 2