blob: ebd18177b2056998b4da806b48a89fa36503e64d [file] [log] [blame]
Guido van Rossume8769491992-08-13 12:14:11 +00001# 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
9def range(*a):
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000010 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(start, stop, step)
20
Guido van Rossume8769491992-08-13 12:14:11 +000021
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
26class Range:
27
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000028 # 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))
Guido van Rossume8769491992-08-13 12:14:11 +000036
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000037 # implement `x` and is also used by print x
38 def __repr__(self):
39 return 'range' + `self.start, self.stop, self.step`
Guido van Rossume8769491992-08-13 12:14:11 +000040
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000041 # implement len(x)
42 def __len__(self):
43 return self.len
Guido van Rossume8769491992-08-13 12:14:11 +000044
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000045 # implement x[i]
46 def __getitem__(self, i):
47 if 0 <= i < self.len:
48 return self.start + self.step * i
49 else:
50 raise IndexError, 'range[i] index out of range'
Guido van Rossume8769491992-08-13 12:14:11 +000051
52
53# Small test program
54
55def test():
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000056 import time, __builtin__
57 print range(10), range(-10, 10), range(0, 10, 2)
58 for i in range(100, -100, -10): print i,
59 print
60 t1 = time.time()
61 for i in range(1000):
62 pass
63 t2 = time.time()
64 for i in __builtin__.range(1000):
65 pass
66 t3 = time.time()
67 print t2-t1, 'sec (class)'
68 print t3-t2, 'sec (built-in)'
Guido van Rossume8769491992-08-13 12:14:11 +000069
70
71test()