Skip to content

Instantly share code, notes, and snippets.

@Djexus
Created December 9, 2011 13:10
Show Gist options
  • Save Djexus/1451464 to your computer and use it in GitHub Desktop.
Save Djexus/1451464 to your computer and use it in GitHub Desktop.
Python's range... in Python
import math
class Range(object):
def __init__(self, start, stop, step):
self.start = start
self.stop = stop
self.step = step
def __repr__(self):
return 'Range(%d, %d, %d)' % (self.start, self.stop, self.step)
def __len__(self):
return max(0, math.ceil((self.stop - self.start) / self.step))
def __reversed__(self):
return Range(self.stop, self.start, -self.step)
def __getitem__(self, index):
if not (-len(self) <= index < len(self)):
raise IndexError('Index out of the range')
return (self.start + (((len(self) + index) % len(self)) * self.step))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment