blob: 8289bc847e0d5c19a046f915442460c53e647b95 [file] [log] [blame]
Guido van Rossume8769491992-08-13 12:14:11 +00001# A simple vector class
2
3
4def vec(*v):
Guido van Rossum7565b931993-12-17 14:23:52 +00005 return apply(Vec, v)
Guido van Rossume8769491992-08-13 12:14:11 +00006
7
8class Vec:
9
Guido van Rossum7565b931993-12-17 14:23:52 +000010 def __init__(self, *v):
Guido van Rossume8769491992-08-13 12:14:11 +000011 self.v = []
12 for x in v:
13 self.v.append(x)
Guido van Rossume8769491992-08-13 12:14:11 +000014
15
16 def fromlist(self, v):
17 self.v = []
18 if type(v) <> type([]):
19 raise TypeError
20 self.v = v[:]
21 return self
22
23
24 def __repr__(self):
25 return 'vec(' + `self.v`[1:-1] + ')'
26
27 def __len__(self):
28 return len(self.v)
29
30 def __getitem__(self, i):
31 return self.v[i]
32
33 def __add__(a, b):
34 # Element-wise addition
35 v = []
36 for i in range(len(a)):
37 v.append(a[i] + b[i])
38 return Vec().fromlist(v)
39
40 def __sub__(a, b):
41 # Element-wise subtraction
42 v = []
43 for i in range(len(a)):
44 v.append(a[i] - b[i])
45 return Vec().fromlist(v)
46
47 def __mul__(self, scalar):
48 # Multiply by scalar
49 v = []
50 for i in range(len(self.v)):
51 v.append(self.v[i]*scalar)
52 return Vec().fromlist(v)
53
54
55
56def test():
57 a = vec(1, 2, 3)
58 b = vec(3, 2, 1)
59 print a
60 print b
61 print a+b
62 print a*3.0
63
64test()