blob: 7fd78e03ea5107a516312436074173ec424a6feb [file] [log] [blame]
Raymond Hettingerfe63faa2003-09-10 21:12:59 +00001'''
2A class which presents the reverse of a sequence without duplicating it.
3From: "Steven D. Majewski" <sdm7g@elvis.med.virginia.edu>
Guido van Rossum102abab1993-10-30 12:38:16 +00004
Raymond Hettingerfe63faa2003-09-10 21:12:59 +00005It works on mutable or inmutable sequences.
Guido van Rossum102abab1993-10-30 12:38:16 +00006
Raymond Hettingerfe63faa2003-09-10 21:12:59 +00007>>> chars = list(Rev('Hello World!'))
8>>> print ''.join(chars)
9!dlroW olleH
10
11The .forw is so you can use anonymous sequences in __init__, and still
12keep a reference the forward sequence. )
13If you give it a non-anonymous mutable sequence, the reverse sequence
14will track the updated values. ( but not reassignment! - another
15good reason to use anonymous values in creating the sequence to avoid
16confusion. Maybe it should be change to copy input sequence to break
17the connection completely ? )
18
19>>> nnn = range(3)
20>>> rnn = Rev(nnn)
21>>> for n in rnn: print n
22...
232
241
250
26>>> for n in range(4, 6): nnn.append(n) # update nnn
27...
28>>> for n in rnn: print n # prints reversed updated values
29...
305
314
322
331
340
35>>> nnn = nnn[1:-1]
36>>> nnn
37[1, 2, 4]
38>>> for n in rnn: print n # prints reversed values of old nnn
39...
405
414
422
431
440
45
46#
47>>> WH = Rev('Hello World!')
48>>> print WH.forw, WH.back
49Hello World! !dlroW olleH
50>>> nnn = Rev(range(1, 10))
51>>> print nnn.forw
52[1, 2, 3, 4, 5, 6, 7, 8, 9]
53>>> print nnn.back
54[9, 8, 7, 6, 5, 4, 3, 2, 1]
55
56>>> rrr = Rev(nnn)
57>>> rrr
58<1, 2, 3, 4, 5, 6, 7, 8, 9>
59
60'''
61
Guido van Rossum102abab1993-10-30 12:38:16 +000062class Rev:
Raymond Hettingerfe63faa2003-09-10 21:12:59 +000063 def __init__(self, seq):
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000064 self.forw = seq
65 self.back = self
Raymond Hettingerfe63faa2003-09-10 21:12:59 +000066
67 def __len__(self):
68 return len(self.forw)
69
70 def __getitem__(self, j):
71 return self.forw[-(j + 1)]
72
73 def __repr__(self):
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000074 seq = self.forw
Raymond Hettingerfe63faa2003-09-10 21:12:59 +000075 if isinstance(seq, list):
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000076 wrap = '[]'
77 sep = ', '
Raymond Hettingerfe63faa2003-09-10 21:12:59 +000078 elif isinstance(seq, tuple):
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000079 wrap = '()'
80 sep = ', '
Raymond Hettingerfe63faa2003-09-10 21:12:59 +000081 elif isinstance(seq, str):
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000082 wrap = ''
83 sep = ''
84 else:
85 wrap = '<>'
86 sep = ', '
Raymond Hettingerfe63faa2003-09-10 21:12:59 +000087 outstrs = [str(item) for item in self.back]
88 return wrap[:1] + sep.join(outstrs) + wrap[-1:]
89
90def _test():
91 import doctest, Rev
92 return doctest.testmod(Rev)
93
94if __name__ == "__main__":
95 _test()