diff --git a/Misc/NEWS.d/next/Tools-Demos/2021-03-13-18-22-58.bpo-43488.bzjZFP.rst b/Misc/NEWS.d/next/Tools-Demos/2021-03-13-18-22-58.bpo-43488.bzjZFP.rst new file mode 100644 index 00000000000000..5e107a15a0382b --- /dev/null +++ b/Misc/NEWS.d/next/Tools-Demos/2021-03-13-18-22-58.bpo-43488.bzjZFP.rst @@ -0,0 +1,9 @@ +What's new in Vector (vector.py) + +1) Added multiplay (Vector and Vector) +2) Added division (Vector and Vector) and (Vector and scalar) +3) Added FloorDiv (Vector and Vector) and (Vector and scalar) +4) Added __mod__ (Vector and Vector) and (Vector and scalar) + +This new methods is very useful! +[It is beta version! By the way we will fix bugs] \ No newline at end of file diff --git a/Tools/demo/vector.py b/Tools/demo/vector.py index da5b3891d18c62..b5a132b67c22d1 100755 --- a/Tools/demo/vector.py +++ b/Tools/demo/vector.py @@ -1,10 +1,13 @@ -#!/usr/bin/env python3 +#!/usr/bin/python +# -*- coding: utf-8 -*- """ A demonstration of classes and their special methods in Python. """ + class Vec: + """A simple vector class. Instances of the Vec class can be constructed from numbers @@ -27,7 +30,9 @@ class Vec: or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) + """ + def __init__(self, *v): self.v = list(v) @@ -50,20 +55,51 @@ def __getitem__(self, i): return self.v[i] def __add__(self, other): + # Element-wise addition - v = [x + y for x, y in zip(self.v, other.v)] + + v = [x + y for (x, y) in zip(self.v, other.v)] return Vec.fromlist(v) def __sub__(self, other): + # Element-wise subtraction - v = [x - y for x, y in zip(self.v, other.v)] - return Vec.fromlist(v) - def __mul__(self, scalar): - # Multiply by scalar - v = [x * scalar for x in self.v] + v = [x - y for (x, y) in zip(self.v, other.v)] return Vec.fromlist(v) + def __mul__(self, other): + if isinstance(other, int) or isinstance(other, float): + m = [x * other for x in self.matrix] + else: + m = [x * y for (x, y) in zip(self.matrix, other.matrix)] + + return Matrix.fromlist(m) + + def __truediv__(self, other): + if isinstance(other, int) or isinstance(other, float): + m = [x / other for x in self.matrix] + else: + m = [x / y for (x, y) in zip(self.matrix, other.matrix)] + + return Matrix.fromlist(m) + + def __floordiv__(self, other): + if isinstance(other, int) or isinstance(other, float): + m = [x // other for x in self.matrix] + else: + m = [x // y for (x, y) in zip(self.matrix, other.matrix)] + + return Matrix.fromlist(m) + + def __mod__(self, other): + if isinstance(other, int) or isinstance(other, float): + m = [x % other for x in self.matrix] + else: + m = [x % y for (x, y) in zip(self.matrix, other.matrix)] + + return Matrix.fromlist(m) + __rmul__ = __mul__ @@ -71,4 +107,5 @@ def test(): import doctest doctest.testmod() + test()