-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ1.py
More file actions
171 lines (147 loc) · 4.46 KB
/
Copy pathQ1.py
File metadata and controls
171 lines (147 loc) · 4.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"""
111901030
Mayank Singla
Coding Assignment 3 - Q1
"""
# %%
def handleError(method):
"""
Decorator Factory function.
Returns a decorator that normally calls the method of a class by forwarding all its arguments to the method.
It surrounds the method calling in try-except block to handle errors gracefully.
"""
def decorator(ref, *args, **kwargs):
"""
Decorator function that surrounds the method of a class in try-except block and call the methods and handles error gracefully.
"""
try:
# Return the same value as that of the method if any
return method(ref, *args, **kwargs)
except Exception as err:
print(type(err))
print(err)
return decorator
class RowVectorFloat:
"""
Represents a row vector of float values.
"""
@handleError
def _validateListValues(self, lst):
"""
Validates the values in the list.
Returns True if correct.
"""
if not isinstance(lst, list):
raise Exception("Invalid input - Expected list")
for i in lst:
if not isinstance(i, float) and not isinstance(i, int):
raise Exception(
f"Invalid type of value received {type(i)}.\nExpected float or int."
)
return True
@handleError
def _validateIndex(self, index):
"""
Validates the input index.
Returns True if correct.
"""
if not isinstance(index, int):
raise Exception(
f"Invalid type of index received {type(index)}.\nExpected int."
)
n = len(self.vec)
if index >= n or index < (-n):
raise Exception(f"Index out of range.")
return True
@handleError
def __init__(self, lst):
"""
Initializes the row vector with the values in the list.
"""
if not self._validateListValues(lst):
return
# Creating a new copy of the list
self.vec = list(lst)
@handleError
def __str__(self):
"""
Returns the string representation of the row vector.
"""
return " ".join(
f"{i:.2f}" if isinstance(i, float) else str(i) for i in self.vec
)
@handleError
def __len__(self):
"""
Returns the length of the row vector.
"""
return len(self.vec)
@handleError
def __getitem__(self, index):
"""
Returns the value at the given index.
"""
if not self._validateIndex(index):
return
return self.vec[index]
@handleError
def __setitem__(self, index, value):
"""
Sets the value at the given index
"""
if not self._validateIndex(index):
return
elif not self._validateListValues([value]):
return
self.vec[index] = value
@handleError
def __add__(self, rv):
"""
Adds two row vectors.
Operator looks for __add__ in left operand.
"""
if not isinstance(rv, RowVectorFloat):
raise Exception("Invalid input - Expected RowVectorFloat")
elif len(self) != len(rv):
raise Exception("Invalid input - Expected same length vectors")
ans = [self.vec[i] + rv.vec[i] for i in range(len(self))]
return RowVectorFloat(ans)
@handleError
def __radd__(self, rv):
"""
Adds two row vectors.
Operator looks for __add__ in right operand.
"""
return self.__add__(rv)
@handleError
def __mul__(self, scalar):
"""
Multiplies a row vector with a scalar.
Operator looks for __mul__ in left operand.
"""
if not isinstance(scalar, (int, float)):
raise Exception("Invalid input - Expected scalar")
ans = [self.vec[i] * scalar for i in range(len(self))]
return RowVectorFloat(ans)
@handleError
def __rmul__(self, scalar):
"""
Multiplies a row vector with a scalar.
Operator looks for __mul__ in right operand.
"""
return self.__mul__(scalar)
if __name__ == "__main__":
# Sample Test Case 1
r = RowVectorFloat([1, 2, 4])
print(r)
print(len(r))
print(r[1])
r[2] = 5
print(r)
r = RowVectorFloat([])
print(len(r))
# Sample Test Case 2
r1 = RowVectorFloat([1, 2, 4])
r2 = RowVectorFloat([1, 1, 1])
r3 = 2 * r1 + (-3) * r2
print(r3)