2

I want to check if m in between l and h. I can write

if m<=h and m>=l

or

m in range(l,h+1)

The latter one looks better, but does it take more than O(1) time?

ShrekFelix
  • 21
  • 2
  • 2
    That should be `m in range(l,h+1)`. – Austin Oct 25 '18 at 16:32
  • `x in range()` is much slower than checking against two integers. – snakecharmerb Oct 25 '18 at 16:34
  • What python version? In python 2, you're creating a list of those elements. If l and m are far apart, that's a lot of memory to use and throw away. In python 3 the range class does this under the hood in very fast time without creating the full list. – g.d.d.c Oct 25 '18 at 16:35
  • 1
    Relevant: https://stackoverflow.com/questions/30081275/why-is-1000000000000000-in-range1000000000000001-so-fast-in-python-3?rq=1 – g.d.d.c Oct 25 '18 at 16:36
  • `x in range(y, z)` is constant time in Python 3. In Python 2, it is linear time – juanpa.arrivillaga Oct 25 '18 at 16:39
  • @snakecharmerb if the `range` object is created ahead of time, it is very comparable (again, assuming Python 3) – juanpa.arrivillaga Oct 25 '18 at 16:42
  • Thanks for the link. I kind of knew range() is like a generator but that __contains__() method under the hood finally solves my doubts. – ShrekFelix Oct 26 '18 at 17:48

2 Answers2

6

O(1):

if m<=h and m>=l:
    ...

O(n) in Python 2, but O(1) in Python 3:

if m in range(l, m+1):
    ...

Better style:

if low <= m <= high:
    ...

Note: The behaviour is different if m can be a non-integer (consider a float, for example).

wim
  • 266,989
  • 79
  • 484
  • 630
  • Thanks but why does the last one work? How is it evaluated? – ShrekFelix Oct 26 '18 at 17:46
  • @FelixYan The evaluation is documented [here](https://docs.python.org/3/reference/expressions.html#comparisons). – wim Oct 26 '18 at 17:50
  • 1
    It's worth noting that `m in range(l, m+1)` and `low <= m <= high` are not equivalent if `m` is a non-integer value (eg. `m = 1.5`). For example, if `low = 0` and `high = 3` then the range test will return false and the comparison operator test will return true. – Dunes Oct 26 '18 at 18:17
0

It's better to use the first one but you can rewrite it like it:

if 1<=m<=h

The function range create a list and in searches if m is in that list. It's worse in performance that two comparisons.

That only applies to python 2, in python 3 both ways are optimal.

  • 1
    Not in python 3. In python 3 the range class does not create a list in memory. Nor does it search it in linear time. – g.d.d.c Oct 25 '18 at 16:35