Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 1 | # A simple vector class |
| 2 | |
| 3 | |
| 4 | def vec(*v): |
Guido van Rossum | 7565b93 | 1993-12-17 14:23:52 +0000 | [diff] [blame] | 5 | return apply(Vec, v) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 6 | |
| 7 | |
| 8 | class Vec: |
| 9 | |
Guido van Rossum | 7565b93 | 1993-12-17 14:23:52 +0000 | [diff] [blame] | 10 | def __init__(self, *v): |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 11 | self.v = [] |
| 12 | for x in v: |
| 13 | self.v.append(x) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 14 | |
| 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 | |
| 56 | def 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 | |
| 64 | test() |