I just filled in the first assignment on course which involves learning Python. The assignment was to make vector class which supports scalar multiplication through operator overloading.
The instructions included these constains:
- There will be one class called
MyVector
- Nothing will be imported in file within that file which contains the class
- The class will accept one argument in constructor, which must be list of numbers
- The class will have two methods:
get_vector
which returns list of numbers of the vector__mul__
(overloaded*
operator) which performs scalar multiplication of two vectors
This is what I have sent:
class MyVector:
"""Vector class"""
coordinates = None
def __init__(self, coordinates):
if not isinstance(coordinates, list):
raise TypeError("Coordinates of vector must me single dimensional array.")
self.coordinates = coordinates
def f(self):
return 'hello world'
def get_vector(self):
return self.coordinates
def dimensions(self):
return len(self.coordinates)
def __mul__(self,other):
if other.dimensions() != self.dimensions():
raise ValueError("Number of dimensions of multiplied vectors must be equal.")
tmp = 0
for index in range(self.dimensions()):
tmp += self.coordinates[index] * other.coordinates[index]
return tmp
''' Just a testing section recommended in the assignment '''
if __name__ == "__main__":
vec1 = MyVector([1,2,5,5,5]) # vektory mohou byt i jine dimenze nez 3!
vec2 = MyVector([1,2,5,5,5])
print(vec1.get_vector()) # Test getting the list of items
dot_product = vec1*vec2 # Multiplication test
print(dot_product)
The homework was OK, but the validation system is bragging that their implementation is faster:
Message: module file vectors.py found
Result ok
Your elapsed time for 10,000 trials, vectors length 300: 0.675 seconds
Our elapsed time for the same setting: 0.383 secondsPoints: 2 out of 2
I'll repeat the relevant section of code here:
def __mul__(self,other):
if other.dimensions() != self.dimensions():
raise ValueError("Number of dimensions of multiplied vectors must be equal.")
tmp = 0
for index in range(self.dimensions()):
tmp += self.coordinates[index] * other.coordinates[index]
return tmp
As you can see, as a seasoned C++ programmer I took naïve approach with indexed for loop. I know that Python has some famous tools to deal with array operation.
Is there some really pythonic way to loop over those two arrays and multiply their elements? Note that primarily I'm looking for pythonic way (since I'm learning Python), optimalization is secondary. I got my 2 points for homework, I'm not submiting it again.