Nedzad Ganic - 9 months ago 36

Python Question

I need to define a variable that contains all possible natural numbers, or at least all numbers from 1 to a million.

I don't want to use the

`range`

EDIT:

If I use the

`range`

The program is giving me a number

`X`

`X`

`var`

Answer

In Python 3.2 and higher, representing a container with all integers from 1 to a million is correctly done with `range`

:

```
>>> positive_nums_to_1M = range(1, 1000001)
>>> 1 in positive_nums_to_1M
True
>>> 1000000 in positive_nums_to_1M
True
>>> 0 in positive_nums_to_1M
False
```

It's extremely efficient; the numbers in the range aren't actually generated, instead the membership (or lack thereof) is computed mathematically.

If you need some equivalent object that supports any positive integer, or need it in Python 2.x, you'll have to write your own class, but it's not hard:

```
from operator import index
class natural_num_range(object):
def __init__(self, maxnum=None):
if maxnum is not None:
maxnum = index(maxnum) # Ensure a true native int (or long)
self.maxnum = maxnum
def __contains__(self, x):
try:
x = index(x)
except TypeError:
return False
return x >= 1 and (self.maxnum is None or x < self.maxnum)
```

That does something similar to `range`

, but without supporting a `start`

or `step`

, and not requiring a `stop`

, so you can do constant time membership tests:

```
>>> natural = natural_num_range()
>>> all(i in natural for i in range(1, 10000000, 10000))
True
>>> any(i in natural for i in range(-100000000, 0, 10000))
False
```

Source (Stackoverflow)