Last active
October 23, 2020 10:03
-
-
Save lablnet/5801812f2149b4cc1c6e2ea2361c4dff to your computer and use it in GitHub Desktop.
Replicate of python range class in Python Class `Range` to understand how it works under the hood.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Range: | |
def __init__(self, start, stop=None, step=1): | |
if step == 0: | |
raise ValueError("Step can not be zero.") | |
if stop is None: | |
start, stop = 0, start | |
# calculate the effective length once | |
self.length = max(0, ((stop - start) + (step - 1)) // step) | |
self.start = start | |
self.step = step | |
self.stop = stop | |
def __str__(self): | |
return "Range(" + str(self.start) + ", " + str(self.stop) + ", " + str(self.step) + ")" | |
def __len__(self): | |
return self.length | |
def __getitem__(self, item): | |
if item < 0: | |
item += len(self) | |
if item >= self.length: | |
raise IndexError("Range object index out of range") | |
return self.start + item * self.step | |
if __name__ == "__main__": | |
r = range(8, 140, 5) | |
R = Range(8, 140, 5) | |
print(list(r)) | |
print(list(R)) | |
print(len(r)) | |
print(len(R)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment