Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 1 | # Example of a generator: re-implement the built-in range function |
| 2 | # without actually constructing the list of values. (It turns out |
| 3 | # that the built-in function is about 20 times faster -- that's why |
| 4 | # it's built-in. :-) |
| 5 | |
| 6 | |
| 7 | # Wrapper function to emulate the complicated range() arguments |
| 8 | |
| 9 | def range(*a): |
| 10 | if len(a) == 1: |
| 11 | start, stop, step = 0, a[0], 1 |
| 12 | elif len(a) == 2: |
| 13 | start, stop = a |
| 14 | step = 1 |
| 15 | elif len(a) == 3: |
| 16 | start, stop, step = a |
| 17 | else: |
| 18 | raise TypeError, 'range() needs 1-3 arguments' |
| 19 | return Range().init(start, stop, step) |
| 20 | |
| 21 | |
| 22 | # Class implementing a range object. |
| 23 | # To the user the instances feel like immutable sequences |
| 24 | # (and you can't concatenate or slice them) |
| 25 | |
| 26 | class Range: |
| 27 | |
| 28 | # initialization -- should be called only by range() above |
| 29 | def init(self, start, stop, step): |
| 30 | if step == 0: |
| 31 | raise ValueError, 'range() called with zero step' |
| 32 | self.start = start |
| 33 | self.stop = stop |
| 34 | self.step = step |
| 35 | self.len = max(0, int((self.stop - self.start) / self.step)) |
| 36 | return self |
| 37 | |
| 38 | # implement `x` and is also used by print x |
| 39 | def __repr__(self): |
| 40 | return 'range' + `self.start, self.stop, self.step` |
| 41 | |
| 42 | # implement len(x) |
| 43 | def __len__(self): |
| 44 | return self.len |
| 45 | |
| 46 | # implement x[i] |
| 47 | def __getitem__(self, i): |
| 48 | if 0 <= i < self.len: |
| 49 | return self.start + self.step * i |
| 50 | else: |
| 51 | raise IndexError, 'range[i] index out of range' |
| 52 | |
| 53 | |
| 54 | # Small test program |
| 55 | |
| 56 | def test(): |
| 57 | import time, builtin |
| 58 | print range(10), range(-10, 10), range(0, 10, 2) |
| 59 | for i in range(100, -100, -10): print i, |
| 60 | print |
| 61 | t1 = time.millitimer() |
| 62 | for i in range(1000): |
| 63 | pass |
| 64 | t2 = time.millitimer() |
| 65 | for i in builtin.range(1000): |
| 66 | pass |
| 67 | t3 = time.millitimer() |
| 68 | print t2-t1, 'msec (class)' |
| 69 | print t3-t2, 'msec (built-in)' |
| 70 | |
| 71 | |
| 72 | test() |