multiple discontinued ranges

cbrown at cbrownsystems.com cbrown at cbrownsystems.com
Thu Nov 11 11:37:52 CET 2010


On Nov 10, 10:02 am, Mel <mwil... at the-wire.com> wrote:
> xoff wrote:
> > I was wondering what the best method was in Python programming for 2
> > discontinued ranges. e.g. I want to use the range 3 to 7 and 17 to 23.
> > Am I obliged to use 2 for loops defining the 2 ranges like this:
>
> > for i in range (3,7):
> >  do bla
> > for i in range (7,17):
> >  do bla
>
> > or is there a more clever way to do this?
>
> One horribly clever way is to concoct a 9-th order polynomial to return
> 3,4,5,6,17,18,19,20,21,22 for input values 0,1,2,3,4,5,6,7,8,9.
>

And one would want one with integer coefficients... truly horribly
clever! A good example of complex is better than complicated...

> The reasonable way is to use two loops as you've done.  If the pattern of
> discontinuous ranges is really important in your application, you'd perhaps
> want to package it up (not tested):
>
> def important_range ():
>     for x in xrange (3, 7):
>         yield x
>     for x in xrange (17,23):
>         yield x
>

Reasonable; but DRY: don't repeat yourself. IMNSHO, better would be:

... def important_range ():
...     for x in [xrange (3, 7), xrange (17,23)]:
...         for y in x:
...             yield y

because face it, you're probably going to add to that list of ranges
anyway, so you should anticipate it (and there's no cost if you don't
end up adding to it).

To extend that notion, I would imagine that itertools.chain is already
basically defined as:

... def chain(*args):
...     for x in args:
...         for y in x:
...             yield y

so important_range() can then be simply defined as:

... def important_range:
...     return chain(xrange (3, 7), xrange (17,23))

Cheers - Chas

> to be used elsewhere as
>
> for v in important_range():
>     # use v ...
>

>         Mel.




More information about the Python-list mailing list