Do you hate Python's range() and want to use R's seq()?
I do. So I implemented R's function in Python.
I wrote a bunch of tests for this for most uses I could think of and they all work. Except the length param, which I did not implement so far. Did not need it. It can be implemented by simply generating the desired number of natural numbers beginning from 1, and then rescaling this to the desired range.
#R style seq()
def seq(from_ = None, to = None, by = None, length = None, along = None):
#init
falling = False
#length
if not length is None:
#TODO: implement when needed
raise ValueError("`length` is not implemented yet")
#along object
if not along is None:
return list(range(1, len(along) + 1))
#if all numeric None, set defaults
if from_ is None and to is None and by is None:
to = 1
from_ = 1
#1 argument
if not from_ is None and to is None and by is None:
#this is actually to
to = from_
from_ = 1
#determine by and adjustment
if from_ > to:
adjustment = -1
#set by
if by is None:
by = -1
else:
adjustment = 1
#set by
if by is None:
by = 1
#impossible by
if from_ > to and by > 0:
raise ValueError("`by` cannot be positive when falling direction")
if from_ < to and by < 0:
raise ValueError("`by` cannot be negative when increasing direction")
if by is 0:
raise ValueError("`by` cannot be zero")
#from, to
if not from_ is None and not to is None:
return list(range(from_, to + adjustment, by))
#if you get here, something is wrong!
raise ValueError("Unknown error. Bad input?")
#convenience wrapper
def seq_along(x):
return(seq(along = x))