Ask Your Question

How do I store a function's results for repeated calls?

asked 2020-02-25 06:40:19 -0600

Blrp gravatar image

In Mathematica one can do this:

factors[n_] := factors[n] = FactorInteger[n]

Then, the first time you call factors[2^385-1], the result is computed, stored, and returned. Next time you make the call, no computation is needed, and the result is returned immediately. How do I do this in Sage?

edit retag flag offensive close merge delete


Look up generator functions and the yeld statement in a Python tutorial...R that this excellent free book has a couple of relevant examples.

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2020-02-26 03:04:18 -0600 )edit

1 answer

Sort by » oldest newest most voted

answered 2020-02-26 04:25:54 -0600

FrédéricC gravatar image

something like that

def facto(n):
    return factor(n)
edit flag offensive delete link more


Awesome! I didn't think it would be that simple.

Blrp gravatar imageBlrp ( 2020-02-26 05:30:09 -0600 )edit

Thank you, Frederic. I ignored the existence of the @cached_function decorator.

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2020-02-26 11:18:24 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2020-02-25 06:40:19 -0600

Seen: 39 times

Last updated: Feb 26