[Tutor] creating a range above & below a given number

Gonzalo Garcia-Perate gonzillaaa at gmail.com
Sun Jun 7 16:08:32 CEST 2009


 the solution laid somewhere in between:

def within_range(self, n, n2, threshold=5):
        if n in range(n2-threshold, n2+threshold+1) and n <
n2+threshold or n > n2 + threshold : return True
        return False

This seems a bit more pythonic than my original function. Thank you both.

2009/6/6 Alan Gauld <alan.gauld at btinternet.com>:
>
> "Gonzalo Garcia-Perate" <gonzillaaa at gmail.com> wrote
>
>> Hello tutor, What's the simplest way of creating a list with a range
>> of numbers above and below a given number?
>> ...
>> this works fine, but is there a simpler way of doing it? a one liner?  :)
>
> I'd probably use a list comprehesion:
>
> L = [n for n in range(lower, upper+!) if n < median-threshold or  n >
> medianthreshold]
>
> eg:
>
>>>> [n for n in range(5,21) if n < 10 or n > 16]
>
> [5, 6, 7, 8, 9, 17, 18, 19, 20]
>>>>
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list