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

Gonzalo Garcia-Perate gonzillaaa at gmail.com
Sun Jun 7 19:17:51 CEST 2009


Emile, Kent thank you both for your reply, after sending my previous
email I realised that it wasn't working as expected in all cases.

this does work:

def within_range_final(self, n, n2, threshold=5):
     return n in range(n2-threshold, n2+threshold+1)

What I have is an ultrasound sensor that gives me a range from 0cm to
6m, what I'm testing is if the new reading goes beyond a threshold and
log it subsequently. So n is the previous reading, n2 is the new
reading and threshold is what I set to be a significant change, 5cm in
the default case.

Thanks again for your help.

2009/6/7 Kent Johnson <kent37 at tds.net>:
> On Sun, Jun 7, 2009 at 10:08 AM, Gonzalo
> Garcia-Perate<gonzillaaa at gmail.com> wrote:
>>  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 is a bit strange and I doubt it does what you want:
>
> In [36]: def within_range(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
>
> In [37]: within_range(10, 11, 5)
> Out[37]: True
>
> In [38]: within_range(20, 11, 5)
> Out[38]: True
>
> Your conditional is equivalent to
> (n in range(n2-threshold, n2+threshold+1) and n < n2+threshold) or n >
> n2 + threshold
>
> which will be true for any n > n2 + threshold.
>
> Can you describe in words what you are trying to test? If you want to
> know if n is in the range n2-threshold to n2+threshold, just test it
> directly:
>  if n2-threshold <= n <= n2+threshold:
>
> If you also want to ensure that n is an integer then use
>  if n==int(n) and (n2-threshold <= n <= n2+threshold):
> or
>  if isinstance(n, int) and (n2-threshold <= n <= n2+threshold):
>
> Kent
>


More information about the Tutor mailing list