]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | '''\r |
2 | A class which presents the reverse of a sequence without duplicating it.\r | |
3 | From: "Steven D. Majewski" <sdm7g@elvis.med.virginia.edu>\r | |
4 | \r | |
5 | It works on mutable or inmutable sequences.\r | |
6 | \r | |
7 | >>> chars = list(Rev('Hello World!'))\r | |
8 | >>> print ''.join(chars)\r | |
9 | !dlroW olleH\r | |
10 | \r | |
11 | The .forw is so you can use anonymous sequences in __init__, and still\r | |
12 | keep a reference the forward sequence. )\r | |
13 | If you give it a non-anonymous mutable sequence, the reverse sequence\r | |
14 | will track the updated values. ( but not reassignment! - another\r | |
15 | good reason to use anonymous values in creating the sequence to avoid\r | |
16 | confusion. Maybe it should be change to copy input sequence to break\r | |
17 | the connection completely ? )\r | |
18 | \r | |
19 | >>> nnn = range(3)\r | |
20 | >>> rnn = Rev(nnn)\r | |
21 | >>> for n in rnn: print n\r | |
22 | ...\r | |
23 | 2\r | |
24 | 1\r | |
25 | 0\r | |
26 | >>> for n in range(4, 6): nnn.append(n) # update nnn\r | |
27 | ...\r | |
28 | >>> for n in rnn: print n # prints reversed updated values\r | |
29 | ...\r | |
30 | 5\r | |
31 | 4\r | |
32 | 2\r | |
33 | 1\r | |
34 | 0\r | |
35 | >>> nnn = nnn[1:-1]\r | |
36 | >>> nnn\r | |
37 | [1, 2, 4]\r | |
38 | >>> for n in rnn: print n # prints reversed values of old nnn\r | |
39 | ...\r | |
40 | 5\r | |
41 | 4\r | |
42 | 2\r | |
43 | 1\r | |
44 | 0\r | |
45 | \r | |
46 | #\r | |
47 | >>> WH = Rev('Hello World!')\r | |
48 | >>> print WH.forw, WH.back\r | |
49 | Hello World! !dlroW olleH\r | |
50 | >>> nnn = Rev(range(1, 10))\r | |
51 | >>> print nnn.forw\r | |
52 | [1, 2, 3, 4, 5, 6, 7, 8, 9]\r | |
53 | >>> print nnn.back\r | |
54 | [9, 8, 7, 6, 5, 4, 3, 2, 1]\r | |
55 | \r | |
56 | >>> rrr = Rev(nnn)\r | |
57 | >>> rrr\r | |
58 | <1, 2, 3, 4, 5, 6, 7, 8, 9>\r | |
59 | \r | |
60 | '''\r | |
61 | \r | |
62 | class Rev:\r | |
63 | def __init__(self, seq):\r | |
64 | self.forw = seq\r | |
65 | self.back = self\r | |
66 | \r | |
67 | def __len__(self):\r | |
68 | return len(self.forw)\r | |
69 | \r | |
70 | def __getitem__(self, j):\r | |
71 | return self.forw[-(j + 1)]\r | |
72 | \r | |
73 | def __repr__(self):\r | |
74 | seq = self.forw\r | |
75 | if isinstance(seq, list):\r | |
76 | wrap = '[]'\r | |
77 | sep = ', '\r | |
78 | elif isinstance(seq, tuple):\r | |
79 | wrap = '()'\r | |
80 | sep = ', '\r | |
81 | elif isinstance(seq, str):\r | |
82 | wrap = ''\r | |
83 | sep = ''\r | |
84 | else:\r | |
85 | wrap = '<>'\r | |
86 | sep = ', '\r | |
87 | outstrs = [str(item) for item in self.back]\r | |
88 | return wrap[:1] + sep.join(outstrs) + wrap[-1:]\r | |
89 | \r | |
90 | def _test():\r | |
91 | import doctest, Rev\r | |
92 | return doctest.testmod(Rev)\r | |
93 | \r | |
94 | if __name__ == "__main__":\r | |
95 | _test()\r |