Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created February 28, 2010 23:24
Show Gist options
  • Save pyrtsa/317910 to your computer and use it in GitHub Desktop.
Save pyrtsa/317910 to your computer and use it in GitHub Desktop.
def crange(*args)
from __future__ import print_function
def crange(*args):
"""crange([start,] stop[, step]) -> xrange object
Make a closed integer range like xrange but with inclusive stop index,
unless it is not reachable with the given step size.
Examples:
>>> for x in crange(-2,2): print(x, end=' ')
-2 -1 0 1 2
>>> for x in crange(-4,1,2): print(x, end=' ')
-4 -2 0
>>> for x in crange(0,9,3): print(x, end=' ')
0 3 6 9
>>> for x in crange(9,-2,-3): print(x, end=' ')
9 6 3 0
>>> len(crange(0, 100, 1))
101
>>> len(crange(0, 100, -10))
0
"""
a,n = args,len(args)
start,stop,step = (0,a[0],1) if n==1 else (a[0],a[1],1) if n==2 else a
stop += sign(step)
return xrange(start, stop, step)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment