[Tutor] creating a range above & below a given number
kent37 at tds.net
Sun Jun 7 21:32:18 CEST 2009
On Sun, Jun 7, 2009 at 1:17 PM, Gonzalo
Garcia-Perate<gonzillaaa at gmail.com> wrote:
> 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.
So why not use simple conditionals?
You may not realize that range(a, b) creates a new list and 'n in
range(a, b)' seaches the list for n. Numeric comparisons are much less
work and also express your intent clearly.
More information about the Tutor