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

Kent Johnson kent37 at tds.net
Sun Jun 7 19:04:39 CEST 2009


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