/Demo/classes/Rev.py

http://unladen-swallow.googlecode.com/ · Python · 95 lines · 93 code · 0 blank · 2 comment · 0 complexity · e8b6a62f19162bab884894634538e095 MD5 · raw file

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