Skip to content

Instantly share code, notes, and snippets.

@Demonstrandum
Created October 4, 2022 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Demonstrandum/0472833113d207686fd522bbb23cdb6c to your computer and use it in GitHub Desktop.
Save Demonstrandum/0472833113d207686fd522bbb23cdb6c to your computer and use it in GitHub Desktop.
Vector class from Python tuple.
class Vec(tuple):
def __new__(cls, x, y=None, z=None):
if y is None:
return super(Vec, cls).__new__(cls, x)
if z is None:
return super(Vec, cls).__new__(cls, (x, y))
return super(Vec, cls).__new__(cls, (x, y, z))
def dot(self, other):
return sum(x0 * x1 for (x0, x1) in zip(self, other))
def __add__(self, other):
return Vec(x0 + x1 for (x0, x1) in zip(self, other))
def __sub__(self, other):
return Vec(x0 - x1 for (x0, x1) in zip(self, other))
def __mul__(self, other):
if isinstance(other, (int, float)):
return Vec(other * x0 for x0 in self)
return Vec(x0 * x1 for (x0, x1) in zip(self, other))
def __rmul__(self, other):
return self.__mul__(other)
v = Vec(1, 2) + Vec(2, 1)
v += Vec(0, 1)
v *= 3
print(2 * v, v.dot(v))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment