Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 1 | # A simple vector class |
| 2 | |
| 3 | |
| 4 | def vec(*v): |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +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 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame^] | 10 | def __init__(self, *v): |
| 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 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame^] | 16 | def fromlist(self, v): |
| 17 | self.v = [] |
| 18 | if type(v) <> type([]): |
| 19 | raise TypeError |
| 20 | self.v = v[:] |
| 21 | return self |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 22 | |
| 23 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame^] | 24 | def __repr__(self): |
| 25 | return 'vec(' + `self.v`[1:-1] + ')' |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 26 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame^] | 27 | def __len__(self): |
| 28 | return len(self.v) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 29 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame^] | 30 | def __getitem__(self, i): |
| 31 | return self.v[i] |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 32 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame^] | 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) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 39 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame^] | 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) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 46 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame^] | 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) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 53 | |
| 54 | |
| 55 | |
| 56 | def test(): |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame^] | 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 |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 63 | |
| 64 | test() |