on a very slow function

Christian Gollwitzer auriocus at gmx.de
Mon Oct 2 01:19:14 EDT 2017


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.
	Christian


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /