[Tutor] lottery problem (Was Re: (no subject))

Peter Otten __peter__ at web.de
Fri Dec 19 10:32:15 CET 2014

```Adam Jensen wrote:

> Side note: if one were to only import specific functions from a module,
> would the load time and memory consumption be smaller? Example, is:
>
> from random import randint, seed
>
> smaller and faster than:
>
> import random

Basically

from random import randint, seed

is equivalent to

import random
randint = random.randint
seed = random.seed
del random

>From that you can deduce that the whole random module is loaded into memory
in both cases. A small speed advantage may be caused when the attribute
lookup is avoided in a tight loop

\$ python3 -m timeit -s 'import random' 'random.randint'
10000000 loops, best of 3: 0.0925 usec per loop
\$ python3 -m timeit -s 'from random import randint' 'randint'
10000000 loops, best of 3: 0.0356 usec per loop

but the actual randint() function call is so "heavy" that this speedup is
lost in the noise when you actually invoke the function:

\$ python3 -m timeit -s 'from random import randint' 'randint(0, 42)'
100000 loops, best of 3: 3.73 usec per loop
\$ python3 -m timeit -s 'import random' 'random.randint(0, 42)'
100000 loops, best of 3: 3.82 usec per loop

> Side side note: since 'i' isn't being used, is there a way to loop (within
> the list comprehension) without the 'i'? For example, to generate three
> random numbers:
>
> [randint(1,10) for i in range(3)]  # This works.
> [randint(1,10) for range(3)]  # This does not work.

No, but in numpy you can express it directly

numpy.random.randint(1, 10, 3)

or -- if you go back to the original problem -- with some effort:

>>> N = 3
>>> numpy.random.randint(1, 10, N) + numpy.arange(0, N*10, 10)
array([ 5, 11, 27])

In return the latter is likely significantly more efficient for large N than
the generic list comprehension.

```