Skip to content

Instantly share code, notes, and snippets.

@magmel48
Created August 22, 2016 09:27
Show Gist options
  • Save magmel48/7907ab87328afb658b29f75b7b85c126 to your computer and use it in GitHub Desktop.
Save magmel48/7907ab87328afb658b29f75b7b85c126 to your computer and use it in GitHub Desktop.
"""
Write a class representing two-dimensional vector (with x and y coordinates),
which supports the following operations:
1. Addition of two vectors: v1 + v2
2. Subtraction of two vectors: v1 - v2
3. Dot product of two vectors:
a. Using operator v1 * v2
b. Using method v1.dot(v2)
c. Using class method Vector2d.dot(v1, v2)
4. Vector length property:
a. v.length
5. String representation: str(v)
"""
from math import sqrt
class Vector:
@classmethod
def dot(cls, first, second):
return first.x * second.x + first.y * second.y
@property
def length(self):
return sqrt(self.x * self.x + self.y * self. y)
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Vector.dot(self, other)
def __str__(self):
return '({0}, {1})'.format(self.x, self.y)
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.x == other.x and self.y == other.y)
def dot(self, other):
return Vector.dot(self, other)
v1 = Vector(1, 2)
v2 = Vector(2, 3)
assert v1 + v2 == Vector(3, 5)
assert v1 - v2 == Vector(-1, -1)
print v1 * v2 == 8
# assert v1.dot(v2) == 8
# assert Vector.dot(v1, v2) == 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment