Created
April 27, 2023 19:09
-
-
Save SamyBencherif/8e1ae64b5ff02e8162b07d17b0909c38 to your computer and use it in GitHub Desktop.
Practical range in Python
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
# unlike range, prange works automatically with reverse ranges, floats, and 0 steps | |
# prange(0,-10) --> 0, -1, -2, -3, -4, -5, -6, -7, -8, -9 | |
# prange(1,2,.1) --> 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9 | |
# prange(0,1,0) --> 0, 0, 0, ... | |
# prange(a,b,c) --> range(a,b,c) # when a,b,c are positive integers and a<b | |
# prange stands for practical range | |
def prange(start, stop=None, step=1): | |
if stop is None: | |
stop = start | |
start = 0 | |
yield start | |
step = abs(step) | |
if stop < start: | |
step = -step | |
while (start - stop) * (start + step - stop) > 0: | |
start += step | |
yield start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment