tags:

views:

96

answers:

4

How can I do something like this:

>>> xrange(4, 10) in xrange(3, 20)
TRUE
A: 
 >>>min(xrange(4, 10)) > min(range(3, 20)) and max(xrange(4, 10)) < max(range(3, 20))
 True
zoli2k
Using `min` and `max` on an `xrange` is inefficient. Use `[0]` and `[-1]` instead.
jleedev
@jleedev: clever note but what if one of the ranges is inverted, that is, a negative number was used as step? ;-)
Nas Banov
@Nas Banov: Good point. You should use min of [0] and [-1] and max of [0] and [1]. How meta.
Scott Stafford
+3  A: 

If you're looking for one set being contained in another set, try:

>>> set(xrange(4, 10)).issubset(set(range(3,20))

If you're looking to compare endpoints since you'll always use ranges for this, than you can just compare the endpoints like @zoli2k.

[EDIT] An edit was requested.

Scott Stafford
Why on earth did I get downvoted? At least leave an obnoxious comment behind!
Scott Stafford
@Nas Banov: Ha, thanks.
Scott Stafford
First I thought the use of `set()` is inefficient but now I realize this is the only solution that works correct with ranges with step!=1, e.g. `range(1,30,3)` or `range(30,1,-1)`. ++
Nas Banov
+5  A: 

How about (min1 >= min2) and (max1 <= max2) ?

(Assuming min1, max1 = 4, 10 and min2, max2 = 3, 20)

Note: You want to compare endpoints without actually making / evaluating the ranges, otherwise it'll be horribly inefficient.

edit: This also works; not better, but prettier imo: min2 <= min1 <= max1 <= max2

tzaman
Shouldn't that be `min2 <= min1 <= max1 <= max2`?
jellybean
@jellybean - depends on whether you want "strict" sub-ranges or not; but I suppose that's better as a default option. Changed.
tzaman
A: 

Given two ranges, you can do this:

>>> a = range(10)
>>> b = range(5,15)
>>> c = range(15,25)
>>> any(x in a for x in b)
True
>>> any(x in a for x in c)
False

This is slightly inefficient, and if have very large (100+ elements) ranges to inspect, it is better for the type of a to be 'set' instead of list. i.e.:

>>> a = set(range(10))

Sets don't have order, but the in operator is much faster.

Jerub