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

Gonzalo Garcia-Perate gonzillaaa at gmail.com
Mon Jun 8 18:56:07 CEST 2009


Kent, Emile thank you both. You're absolutely right, I was going for
range because I thought it made the code more readable/more explicit.
I hadn't taken into account the performance hit of creating the list
and iterating through it. I'm not sure it was more readable either.

the function now reads:
def within_range_final(self, n, n2, threshold=5):
    return n2-threshold <= n <= n2+threshold+1

thanks again for you input.

G.


2009/6/8 Kent Johnson <kent37 at tds.net>:
> On Sun, Jun 7, 2009 at 3:34 PM, Emile van Sebille<emile at fenx.com> wrote:
>
>> To explain why we've tended to suggest using int and minval<val<maxval as
>> tests and avoid the range inclusion test, consider the following timeit
>> results:
>
> The performance penalty for 'in range(...)' is even greater when the
> value is not found, because the entire list must be searched:
>
> kent $ python -m timeit "0 <= 6000 <= 1000"
> 10000000 loops, best of 3: 0.111 usec per loop
>
> kent $ python -m timeit "6 in range(100)"
> 100000 loops, best of 3: 1.89 usec per loop
>
> kent $ python -m timeit "6000 in range(100)"
> 100000 loops, best of 3: 5.55 usec per loop
>
> kent $ python -m timeit "6 in range(1000)"
> 100000 loops, best of 3: 19 usec per loop
>
> kent $ python -m timeit "6000 in range(1000)"
> 10000 loops, best of 3: 55.4 usec per loop
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list