fork download
  1. import collections
  2.  
  3. class SliceView(collections.abc.Sequence):
  4. def __init__(self, seq, start=None, stop=None, step=None):
  5. self.seq = seq
  6. sl = slice(start, stop, step)
  7. self.start, self.stop, self.step = sl.indices(len(seq))
  8. def __len__(self):
  9. return len(range(self.start, self.stop, self.step))
  10. def __getitem__(self, idx):
  11. if isinstance(idx, slice):
  12. start, stop, step = idx.indices(len(self))
  13. return type(self)(self.seq, start, stop, step)
  14. if idx < 0:
  15. idx += self.stop
  16. if idx < self.start:
  17. raise IndexError
  18. else:
  19. idx += self.start
  20. if idx >= self.stop:
  21. raise IndexError
  22. return self.seq[idx]
  23. def __str__(self):
  24. return str(list(self))
  25.  
  26. base = SliceView([1, 2, 3])
  27. print(list(base))
  28. print(list(base[1:]))
  29. print(list(base[1:][1:]))
Success #stdin #stdout 0.04s 9400KB
stdin
Standard input is empty
stdout
[1, 2, 3]
[2, 3]
[2]