0

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.

Danilo
  • 933
  • 9
  • 29

1 Answers1

1

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.

Community
  • 1
  • 1
schwobaseggl
  • 55,463
  • 4
  • 39
  • 63
  • do i need pprint ? i have seen it before but mostly it is used as simple print – Danilo Nov 20 '16 at 13:37
  • decided for myown range class, seems better for the future that i implement it , do you have any idea how to get number of combinations for iteration ? – Danilo Nov 20 '16 at 15:34
  • finally done, like iterator within iterator, great results. Thank you. Still some bugs to fix though, but i am pleased – Danilo Nov 20 '16 at 20:33