Last change
on this file since 6 was 2, checked in by Yuri Dario, 15 years ago |
Initial import for vendor code.
|
-
Property svn:eol-style
set to
native
|
File size:
1000 bytes
|
Line | |
---|
1 | # A simple vector class
|
---|
2 |
|
---|
3 |
|
---|
4 | def vec(*v):
|
---|
5 | return Vec(*v)
|
---|
6 |
|
---|
7 |
|
---|
8 | class Vec:
|
---|
9 |
|
---|
10 | def __init__(self, *v):
|
---|
11 | self.v = list(v)
|
---|
12 |
|
---|
13 | def fromlist(self, v):
|
---|
14 | if not isinstance(v, list):
|
---|
15 | raise TypeError
|
---|
16 | self.v = v[:]
|
---|
17 | return self
|
---|
18 |
|
---|
19 | def __repr__(self):
|
---|
20 | return 'vec(' + repr(self.v)[1:-1] + ')'
|
---|
21 |
|
---|
22 | def __len__(self):
|
---|
23 | return len(self.v)
|
---|
24 |
|
---|
25 | def __getitem__(self, i):
|
---|
26 | return self.v[i]
|
---|
27 |
|
---|
28 | def __add__(self, other):
|
---|
29 | # Element-wise addition
|
---|
30 | v = map(lambda x, y: x+y, self, other)
|
---|
31 | return Vec().fromlist(v)
|
---|
32 |
|
---|
33 | def __sub__(self, other):
|
---|
34 | # Element-wise subtraction
|
---|
35 | v = map(lambda x, y: x-y, self, other)
|
---|
36 | return Vec().fromlist(v)
|
---|
37 |
|
---|
38 | def __mul__(self, scalar):
|
---|
39 | # Multiply by scalar
|
---|
40 | v = map(lambda x: x*scalar, self.v)
|
---|
41 | return Vec().fromlist(v)
|
---|
42 |
|
---|
43 |
|
---|
44 |
|
---|
45 | def test():
|
---|
46 | a = vec(1, 2, 3)
|
---|
47 | b = vec(3, 2, 1)
|
---|
48 | print a
|
---|
49 | print b
|
---|
50 | print a+b
|
---|
51 | print a-b
|
---|
52 | print a*3.0
|
---|
53 |
|
---|
54 | test()
|
---|
Note:
See
TracBrowser
for help on using the repository browser.