-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass Vector, LowerCaseDecorator
More file actions
249 lines (213 loc) · 7.43 KB
/
class Vector, LowerCaseDecorator
File metadata and controls
249 lines (213 loc) · 7.43 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import math
class Vector:
"""
Implement the methods below to create an immutable 3D vector class.
Each implemented method will award you half a point.
Magic methods cheatsheet: https://rszalski.github.io/magicmethods
"""
"""
Implement a constructor that takes three coordinates (x, y, z) and stores
them as attributes with the same names in the Vector.
Default value for all coordinates should be 0.
Example:
v = Vector(1.2, 3.5, 4.1)
v.x # 1.2
v = Vector(z=1) # == Vector(0, 0, 1)
"""
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
"""
Implement method `length` that returns the length of the vector
(https://chortle.ccsu.edu/VectorLessons/vch04/vch04_8.html).
Example:
Vector(2, 3, 4).length() # 5.38...
"""
def length(self):
return math.sqrt(self.x * self.x + self.y*self.y + self.z*self.z)
"""
Implement vector addition and subtraction using `+` and `-` operators.
Both operators should return a new vector and not modify its operands.
If the second operand isn't a vector, raise ValueError.
Example:
Vector(1, 2, 3) + Vector(4, 5, 6) # Vector(5, 7, 8)
Vector(1, 2, 3) - Vector(4, 5, 6) # Vector(-3, -3, -3)
Hint:
You can use isinstance(object, class) to check whether `object` is an instance of `class`.
"""
def __add__(self,other):
if(isinstance(other,Vector)):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
else:
raise ValueError()
def __sub__(self, other):
if(isinstance(other, Vector)):
return Vector(self.x - other.x,self.y - other.y,self.z - other.z)
else:
raise ValueError()
"""
Implement vector negation using the unary `-` operator.
Return a new vector, don't modify the input vector.
Example:
-Vector(1, 2, 3) # Vector(-1, -2, -3)
"""
def __neg__(self):
return Vector(-self.x, -self.y, -self.z)
"""
Implement multiplication and division by scalar using `*` and `/` operators.
Both operators should return a new Vector and not modify the input vector.
If the second operand isn't `int` or `float`, raise ValueError.
Example:
Vector(1, 2, 3) * 4 # Vector(4, 8, 12)
Vector(2, 4, 6) / 2 # Vector(1, 2, 3)
Hint:
Division with the `/` operator uses the magic method `__truediv__` in Python 3.
"""
def __mul__(self, other):
if (isinstance(other, int) or isinstance(other, float)):
return Vector(self.x * other, self.y * other, self.z * other)
else:
raise ValueError()
def __truediv__(self, other):
if (isinstance(other, int) or isinstance(other, float)):
return Vector(self.x / other, self.y / other, self.z / other)
else:
raise ValueError()
"""
Implement the `==` comparison operator for Vector that returns True if both vectors have the same attributes.
If the second operand isn't a vector, return False.
Example:
Vector(1, 1, 1) == Vector(1, 1, 1) # True
Vector(1, 1, 1) == Vector(2, 1, 1) # False
Vector(1, 2, 3) == 5 # False
"""
def __eq__(self, other):
if (isinstance(other, Vector)):
if (self.x == other.x and self.y == other.y and self.z == other.z):
return True
else:
return False
"""
Implement *property* `unit` that will return the unit vector of this vector
(vector with the same direction and length one).
If the vector has length zero, return a zero vector (Vector(0, 0, 0)).
Example:
Vector(0, 8, 0).unit # Vector(0, 1, 0)
"""
@property
def unit(self):
if(self.length() ==0):
return Vector(0, 0, 0)
else:
l = self.length()
return Vector(self.x / l, self.y / l, self.z / l)
"""
Implement string representation of Vector in the form `(x, y, z)`.
Example:
str(Vector(1, 2, 3)) # (1, 2, 3)
print(Vector(0, 0, 0)) # (0, 0, 0)
"""
def __str__(self):
return ("(" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + ")")
"""
Implement indexing for the vector, both for reading and writing.
If the index is out of range (> 2), raise IndexError.
Example:
v = Vector(1, 2, 3)
v[0] # 1
v[2] # 3
v[1] = 5 # v.y == 5
v[10] # raises IndexError
"""
def __setitem__(self, key, value):
if key == 0:
self.x = value
elif key == 1:
self.y = value
elif key == 2:
self.z = value
else:
raise IndexError
def __getitem__(self, key):
if key == 0:
return self.x
elif key == 1:
return self.y
elif key == 2:
return self.z
else:
raise IndexError
"""
Implement the iterator protocol for the vector.
Hint:
Use `yield`.
Example:
v = Vector(1, 2, 3)
for x in v:
print(x) # prints 1, 2, 3
"""
def __next__(self, n = 0):
if n >= 0 and n < 3:
yield self[n]
n += 1
else:
raise IndexError
class LowerCaseDecorator:
"""
Points: 1
Implement the `decorator` design pattern.
LowerCaseDecorator should decorate a file which will be passed to its constructor.
It should make all characters/strings written to the file lowercase.
It is enough to support the `write` and `writelines` methods of file.
Example:
with open("file.txt", "w") as f:
decorated = LowerCaseDecorator(f)
decorated.write("Hello World\n")
decorated.writelines(["Nice to MEET\n", "YOU"])
file.txt content after the above code is executed:
hello world
nice to meet
you
"""
/* def __init__(self, f):
self.f = f
def LowerCaseDecorator(f):
def wrapper(*args, **kwargs):
return f(*args, **kwargs).lower()
return wrapper
@LowerCaseDecorator
def write(self, f):
self.write(f)
@LowerCaseDecorator
def writelines(self, f):
self.write(f) */
class BonusObservable:
"""
Points: 1 (bonus)
Implement the `observer` design pattern.
Observable should have a `subscribe` method for adding new subscribers.
It should also have a `notify` method that calls all of the stored subscribers and passes them its parameters.
Example:
obs = BonusObservable()
def fn1(x):
print("fn1: {}".format(x))
def fn2(x):
print("fn2: {}".format(x))
unsub1 = obs.subscribe(fn1) # fn1 will be called everytime obs is notified
unsub2 = obs.subscribe(fn2) # fn2 will be called everytime obs is notified
obs.notify(5) # should call fn1(5) and fn2(5)
unsub1() # fn1 is no longer subscribed
obs.notify(6) # should call fn2(6)
"""
def subcribe(self, subscriber):
"""
Add subscriber to collection of subscribers.
Return a function that will remove this subscriber from the collection when called.
"""
pass
def notify(self):
"""
Pass all parameters given to this function to all stored subscribers by calling them.
"""
pass