Skip to content

Instantly share code, notes, and snippets.

@SamyBencherif
Created April 27, 2023 19:09
Show Gist options
  • Save SamyBencherif/8e1ae64b5ff02e8162b07d17b0909c38 to your computer and use it in GitHub Desktop.
Save SamyBencherif/8e1ae64b5ff02e8162b07d17b0909c38 to your computer and use it in GitHub Desktop.
Practical range in Python
# 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