Danilo Danilo - 15 days ago 5
Python Question

Python range with tuple,list as imput

is there a way to hack range function to accept tuples?

like this :

range( (0,0,0), (10,1,5) , (1,1,1) )

i want to use range on custom point class , it can return list,tuple or class object. I tired the for loops, while loops, generators, list comprehensions, maps and filtering. They are very good on smaller numbers <10 but on larger numbers they take too long. Is there a way this can be done?

And i plan to use this function to describe space, for example you have available points of some 3d box, you need to check some other 3d box if it can be located in some point withing the bigger 3d box, so i would need to call this range 2 times in this example. One : for the available points in bigger 3d box, and second to check every point in smaller 3d box if it is empty in bigger box. So if i have range functions that take 2 minutes this one will need 4 minutes + exec time for any function to be done. Now this project must be on greater scale, not only 1 small box but several.

Answer

Here is a little custom range function, that is based on zipping, unpacking and itertools.product:

>>> from itertools import product
>>> from pprint import pprint

>>> def my_range(start, stop, step):
...     return product(*(xrange(*x) for x in zip(start, stop, step)))

>>> r = ((0, 0, 0), (5, 2, 4), (1, 1, 1))

>>> pprint(list(my_range(*r)))
[(0, 0, 0),
(0, 0, 1),
(0, 0, 2),
(0, 0, 3),
(0, 1, 0),
(0, 1, 1),
# ...
(4, 1, 1),
(4, 1, 2),
(4, 1, 3)]

However, when performance becomes important, you should look at implementing your own range class along the lines of the Python3 range object, as these points become numerous quite fast and there much cleverer ways to check whether one box is contained in another one then iterating over all points.

Comments