lalala33rfs

Untitled

Nov 17th, 2019
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. import functools
  2.  
  3.  
  4. class Vector:
  5.     def __init__(self, list):
  6.         self.list = list
  7.  
  8.     def __add__(self, other):
  9.         if len(self.list) != len(other.list):
  10.             raise TypeError()
  11.         return Vector([x + y for (x, y) in zip(self.list, other.list)])
  12.  
  13.     def __sub__(self, other):
  14.         if len(self.list) != len(other.list):
  15.             raise TypeError()
  16.         return Vector([x - y for (x, y) in zip(self.list, other.list)])
  17.  
  18.     def __mul__(self, other):
  19.         if isinstance(other, Vector):
  20.             if len(self.list) != len(other.list):
  21.                 raise TypeError()
  22.             return sum([x * y for (x, y) in zip(self.list, other.list)])
  23.  
  24.         return [x * other for x in self.list]
  25.  
  26.     def __rmul__(self, other):
  27.         return self.__mul__(other)
  28.  
  29.     def __eq__(self, other):
  30.         return functools.reduce(
  31.             (lambda a, b: a and b),
  32.             [x == y for (x, y) in zip(self.list, other.list)]
  33.         )
  34.  
  35.     def __len__(self):
  36.         return len(self.list)
  37.  
  38.     def __getitem__(self, i):
  39.         return self.list[i]
  40.  
  41.     def __setitem__(self, key, value):
  42.         self.list[key] = value
  43.  
  44.     def __str__(self):
  45.         return '[' + ', '.join(map(str, self.list)) + ']'
  46.  
  47.     def __iadd__(self, other):
  48.         if len(self.list) != len(other.list):
  49.             raise TypeError()
  50.         self.list = [x + y for (x, y) in zip(self.list, other.list)]
  51.         return self
  52.  
  53.     def __imul__(self, other):
  54.         if isinstance(other, Vector):
  55.             if len(self.list) != len(other.list):
  56.                 raise TypeError()
  57.             return sum([x * y for (x, y) in zip(self.list, other.list)])
  58.  
  59.         self.list = [x * other for x in self.list]
  60.         return self
  61.  
  62.     def __isub__(self, other):
  63.         if len(self.list) != len(other.list):
  64.             raise TypeError()
  65.         self.list = [x - y for (x, y) in zip(self.list, other.list)]
  66.         return self
  67.  
  68.     def __abs__(self):
  69.         return sum([x ** 2 for x in self.list]) ** 0.5
Advertisement
Add Comment
Please, Sign In to add comment