forked from UWPCE-PythonCert/ProgrammingInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.py
More file actions
50 lines (43 loc) · 1.2 KB
/
vector.py
File metadata and controls
50 lines (43 loc) · 1.2 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
"""
Vector type with +, * redefined as Vector addition and dot product
"""
class Vector(list):
def __repr__(self):
"""
String representation, uses list (superclass) representation
"""
return 'Vector({})'.format(super().__repr__())
def __add__(self, v):
"""
redefine + as element-wise Vector sum
"""
if len(self) != len(v):
raise TypeError("Vector can only be added to a sequence of the same length")
else:
return Vector([x1 + x2 for x1, x2 in zip(self, v)])
def __mul__(self, v):
"""
redefine * as Vector dot product
"""
if len(self) != len(v):
raise TypeError("Vector can only be multiplied with a sequence of the same length")
else:
return sum([x1 * x2 for x1, x2 in zip(self, v)])
if __name__ == '__main__':
l1 = [1, 2, 3]
l2 = [4, 5, 6]
v1 = Vector(l1)
v2 = Vector(l2)
print('l1')
print(l1)
print('l1 + l2')
print(l1 + l2)
# print(l1 * l2) # TypeError
print('zip(l1, l2)')
print(zip(l1, l2))
print('v1')
print(v1)
print('v1 + v2')
print(v1 + v2)
print('v1 * v2')
print(v1 * v2)