MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / Vector

Class Vector

linear_algebra/src/lib.py:30–193  ·  view source on GitHub ↗

This class represents a vector of arbitrary size. You need to give the vector components. Overview of the methods: __init__(components: Collection[float] | None): init the vector __len__(): gets the size of the vector (number of components) __str__(): returns a

Source from the content-addressed store, hash-verified

28
29
30class Vector:
31 """
32 This class represents a vector of arbitrary size.
33 You need to give the vector components.
34
35 Overview of the methods:
36
37 __init__(components: Collection[float] | None): init the vector
38 __len__(): gets the size of the vector (number of components)
39 __str__(): returns a string representation
40 __add__(other: Vector): vector addition
41 __sub__(other: Vector): vector subtraction
42 __mul__(other: float): scalar multiplication
43 __mul__(other: Vector): dot product
44 copy(): copies this vector and returns it
45 component(i): gets the i-th component (0-indexed)
46 change_component(pos: int, value: float): changes specified component
47 euclidean_length(): returns the euclidean length of the vector
48 angle(other: Vector, deg: bool): returns the angle between two vectors
49 """
50
51 def __init__(self, components: Collection[float] | None = None) -> None:
52 """
53 input: components or nothing
54 simple constructor for init the vector
55 """
56 if components is None:
57 components = []
58 self.__components = list(components)
59
60 def __len__(self) -> int:
61 """
62 returns the size of the vector
63 """
64 return len(self.__components)
65
66 def __str__(self) -> str:
67 """
68 returns a string representation of the vector
69 """
70 return "(" + ",".join(map(str, self.__components)) + ")"
71
72 def __add__(self, other: Vector) -> Vector:
73 """
74 input: other vector
75 assumes: other vector has the same size
76 returns a new vector that represents the sum.
77 """
78 size = len(self)
79 if size == len(other):
80 result = [self.__components[i] + other.component(i) for i in range(size)]
81 return Vector(result)
82 else:
83 raise Exception("must have the same size")
84
85 def __sub__(self, other: Vector) -> Vector:
86 """
87 input: other vector

Callers 15

__add__Method · 0.85
__sub__Method · 0.85
__mul__Method · 0.85
copyMethod · 0.85
zero_vectorFunction · 0.85
unit_basis_vectorFunction · 0.85
random_vectorFunction · 0.85
test_componentMethod · 0.85
test_strMethod · 0.85
test_sizeMethod · 0.85
test_euclidean_lengthMethod · 0.85
test_addMethod · 0.85

Calls

no outgoing calls

Tested by 11

test_componentMethod · 0.68
test_strMethod · 0.68
test_sizeMethod · 0.68
test_euclidean_lengthMethod · 0.68
test_addMethod · 0.68
test_subMethod · 0.68
test_mulMethod · 0.68
test_axpyMethod · 0.68
test_copyMethod · 0.68
test_change_componentMethod · 0.68
test__mul__matrixMethod · 0.68