[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

on a very slow function

Am 01.10.17 um 23:27 schrieb Daniel Bastos:
> def make_sequence_non_recursive(N, x0 = 2, c = -1):
>    "What's wrong with this function?  It's very slow."
>    last = x0
>    def sequence():
>      nonlocal last
>      next = last
>      last = last**2 + c
>      return next % N
>    return sequence
> It crawls pretty soon.  Please advise?  Thank you.

You seem to do modular arithmetics with modulus N. You can take the 
modulus after each single operation. This line:

	last = last**2 + c

will quadratically grow the internal state of the generator. Instead, 
you should write

	last = (last**2 + c) % N

If I have understood what it does, then the result should be the same. 
Furthermore, as Chris said, Python has built-in generators for this thing.