1 # A class which presents the reverse of a sequence without duplicating it.
2 # From: "Steven D. Majewski" <sdm7g@elvis.med.virginia.edu>
4 # It works on mutable or inmutable sequences.
6 # >>> for c in Rev( 'Hello World!' ) : sys.stdout.write( c )
7 # ... else: sys.stdout.write( '\n' )
11 # The .forw is so you can use anonymous sequences in __init__, and still
12 # keep a reference the forward sequence. )
13 # If you give it a non-anonymous mutable sequence, the reverse sequence
14 # will track the updated values. ( but not reassignment! - another
15 # good reason to use anonymous values in creating the sequence to avoid
16 # confusion. Maybe it should be change to copy input sequence to break
17 # the connection completely ? )
19 # >>> nnn = range( 0, 3 )
20 # >>> rnn = Rev( nnn )
21 # >>> for n in rnn: print n
26 # >>> for n in range( 4, 6 ): nnn.append( n ) # update nnn
28 # >>> for n in rnn: print n # prints reversed updated values
38 # >>> for n in rnn: print n # prints reversed values of old nnn
47 # WH = Rev( 'Hello World!' )
48 # print WH.forw, WH.back
49 # nnn = Rev( range( 1, 10 ) )
55 # Hello World! !dlroW olleH
56 # [1, 2, 3, 4, 5, 6, 7, 8, 9]
57 # [9, 8, 7, 6, 5, 4, 3, 2, 1]
61 # <1, 2, 3, 4, 5, 6, 7, 8, 9>
63 from string
import joinfields
65 def __init__( self
, seq
):
69 return len( self
.forw
)
70 def __getitem__( self
, j
):
71 return self
.forw
[ -( j
+ 1 ) ]
74 if type(seq
) == type( [] ) :
77 elif type(seq
) == type( () ) :
80 elif type(seq
) == type( '' ) :
87 for item
in self
.back
:
88 outstrs
.append( str( item
) )
89 return wrap
[:1] + joinfields( outstrs
, sep
) + wrap
[-1:]