-
-
Save jheiv/1d0efd0a0bc39e73bffd to your computer and use it in GitHub Desktop.
Example of how slicing may be implemented
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
def apply_slice(it, sl): | |
start, stop, step = sl.indices(len(it)) | |
elems = [] | |
i = start | |
if step > 0: | |
while i < stop: | |
elems.append(it[i]) | |
i += step | |
elif step < 0: | |
while i > stop: | |
elems.append(it[i]) | |
i += step | |
# Some type-specific conversions | |
if isinstance(it, str): elems = ''.join(elems) | |
#... | |
return elems | |
#=================================================================================================== | |
# Some string, and some example slices | |
st = "The quick brown fox jumps over the lazy dog" | |
slices = [ | |
slice(0,10,2), | |
slice(None, None, None), | |
slice(None, None, 1), | |
slice(None, None, -1), | |
slice(len(st), -len(st)-1, -1), | |
slice(len(st), -len(st)-1), | |
] | |
# Apply each, and compare the outputs | |
for sl in slices: | |
sliced1 = st[sl] | |
sliced2 = apply_slice(st, sl) | |
try: | |
assert sliced1 == sliced2 | |
print("%-25s %r" % (sl, sliced1)) | |
except AssertionError: | |
print("---") | |
print(sl) | |
print(sliced1) | |
print(sliced2) | |
print("---") | |
''' | |
Output: | |
slice(0, 10, 2) 'Teqik' | |
slice(None, None, None) 'The quick brown fox jumps over the lazy dog' | |
slice(None, None, 1) 'The quick brown fox jumps over the lazy dog' | |
slice(None, None, -1) 'god yzal eht revo spmuj xof nworb kciuq ehT' | |
slice(43, -44, -1) 'god yzal eht revo spmuj xof nworb kciuq ehT' | |
slice(43, -44, None) '' | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment