'''A class which presents the reverse of a sequence without duplicating it.From: "Steven D. Majewski" <sdm7g@elvis.med.virginia.edu>It works on mutable or inmutable sequences.>>> chars = list(Rev('Hello World!'))>>> print ''.join(chars)!dlroW olleHThe .forw is so you can use anonymous sequences in __init__, and stillkeep a reference the forward sequence. )If you give it a non-anonymous mutable sequence, the reverse sequencewill track the updated values. ( but not reassignment! - anothergood reason to use anonymous values in creating the sequence to avoidconfusion. Maybe it should be change to copy input sequence to breakthe connection completely ? )>>> nnn = range(3)>>> rnn = Rev(nnn)>>> for n in rnn: print n...210>>> for n in range(4, 6): nnn.append(n) # update nnn...>>> for n in rnn: print n # prints reversed updated values...54210>>> nnn = nnn[1:-1]>>> nnn[1, 2, 4]>>> for n in rnn: print n # prints reversed values of old nnn...54210#>>> WH = Rev('Hello World!')>>> print WH.forw, WH.backHello World! !dlroW olleH>>> nnn = Rev(range(1, 10))>>> print nnn.forw[1, 2, 3, 4, 5, 6, 7, 8, 9]>>> print nnn.back[9, 8, 7, 6, 5, 4, 3, 2, 1]>>> rrr = Rev(nnn)>>> rrr<1, 2, 3, 4, 5, 6, 7, 8, 9>'''class Rev:def __init__(self, seq):self.forw = seqself.back = selfdef __len__(self):return len(self.forw)def __getitem__(self, j):return self.forw[-(j + 1)]def __repr__(self):seq = self.forwif isinstance(seq, list):wrap = '[]'sep = ', 'elif isinstance(seq, tuple):wrap = '()'sep = ', 'elif isinstance(seq, str):wrap = ''sep = ''else:wrap = '<>'sep = ', 'outstrs = [str(item) for item in self.back]return wrap[:1] + sep.join(outstrs) + wrap[-1:]def _test():import doctest, Revreturn doctest.testmod(Rev)if __name__ == "__main__":_test()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。