if number is 1-2, 4 or 6-8 or 12-28, 30, 32...
Skip Montanaro
skip at pobox.com
Tue Jun 11 09:50:18 EDT 2002
Gustaf> Cliff's solution was really fast, but it took a while to
Gustaf> understand. :)
One thing I frequently forget about is the else: clause for try/except
statements. This lets you isolate as small a piece of code as possible in
the try: clause, making it a bit easier to understand what triggers the
exception:
def isin(n, ranges):
for r in ranges:
try:
s, e = r
except TypeError:
if n == r:
return 1
else:
if s <= n <= e:
return 1
return 0
You could also fold the int case into the tuple case (making it a bit more
uniform), but at a slight cost in performance if you have lots of ints. In
this case, all the try/except statement is responsible for is setting s and
e:
def isin(n, ranges):
for r in ranges:
try:
s, e = r
except TypeError:
s, e = n, n
if s <= n <= e:
return 1
return 0
--
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html
More information about the Python-list
mailing list