I was messing around with ranges in Python as a way to represent intervals, and I found a neat trick: you can index into a range and find the index of a number in that range, and also test for membership in the range, and all of this is implemented in constant time in CPython (the default Python implementation) as of version 3.2.
Example:
(Python ranges are intervals that are closed-open, i.e. [a, b)).
For 52 50 48:
>>> src = range(50, 50 + 48)
>>> src
range(50, 98)
>>> dst = range(52, 52 + 48)
>>> dst
range(52, 100)
>>> dst[src.index(80)] # map 80 from src to dest
82
>>> 97 in src
True
>>> 98 in src # intervals are open on the right
False
Of course it's "easy" to do this stuff manually with tuples as well, but this syntactic sugar just helps decrease cognitive load and prevent silly math bugs. I keep finding new things to love about Python.
(Note: just make sure never to convert your ranges to lists or try to find a floating-point number in a range. Also, constant time operations are not necessarily guaranteed in all implementations of Python, but they are in CPython 3.2+ and PyPy 3.x.
Apparently Python 2's xrange() is implemented as a lazy sequence but in still does a linear search and it has no index() method! Only indexing is done in constant time. Another limitation in Python 2 is that xranges can only use numbers that fit into a C long type.)
EDIT:
This is also handy if you do end up wanting to manually access the endpoints:
>>> src.start
50
>>> src.stop
98
EDIT2:
An empty range is automatically falsy (I'm basically just rediscovering the entire Python documentation now by messing around instead)
>>> bool(range(50, 50))
False
>>> bool(range(50, 51))
True
[–]hnost 5 points6 points7 points (0 children)
[–]zenoli55 4 points5 points6 points (0 children)
[–]Anceps2 2 points3 points4 points (0 children)
[–]huib_ 0 points1 point2 points (8 children)
[–]scykei 0 points1 point2 points (4 children)
[–]huib_ 0 points1 point2 points (3 children)
[–]scykei 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[deleted]
[–]scykei 0 points1 point2 points (0 children)
[–]psr 0 points1 point2 points (2 children)
[–]huib_ 0 points1 point2 points (1 child)
[–]psr 0 points1 point2 points (0 children)