Reputation: 81
I've started a data science course a question in the first assignment is write a function that returns the addition, multiplication and dot product of two vectors as set out in the format below:
def list_mul(u, v):
"""
Given two vectors, calculate and return the following quantities:
- element-wise sum
- element-wise product
- dot product
If the two vectors have different dimensions,
you should raise a ValueError
:param u: first vector (list)
:param v: second vector (list)
:return: the three quantities above
:rtype: list, list, float
:raise ValueError:
"""
I would find this really easy if I could use numpy, but the requirement is to write the function using vanilla python only - we can use things like import math etc, but no custom packages.
I'd be really grateful if someone is able to help or give some advice?
Many thanks,
Andrew
Upvotes: 0
Views: 611
Reputation: 81
Thanks to L. Suurmeijer for your advice on this question. I ended up running with the solution below using zip() function
if len(v)!=len(u):
raise ValueError('inconsistent dimension')
vec_sum=[x+y for x,y in zip(u,v)]
vec_prod = [x * y for x, y in zip(u, v)]
dot_prod=sum(x*y for x,y in zip(u,v))
return vec_sum, vec_prod, dot_prod
Upvotes: 0
Reputation: 43
I don't want to give away a solution, but I'll give some advice instead. I think a decently succinct solution for all 3 operations is possible using list comprehensions.
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
and zip()
Make an iterator that aggregates elements from each of the iterables.
Good luck!
Upvotes: 1