Ask Your Question
0

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

asked 2020-02-25 13:40:19 +0100

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

Comments

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 10:04:18 +0100 )edit

1 Answer

Sort by » oldest newest most voted
1

answered 2020-02-26 11:25:54 +0100

FrédéricC gravatar image

something like that

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

Comments

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

Blrp gravatar imageBlrp ( 2020-02-26 12:30:09 +0100 )edit

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

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2020-02-26 18:18:24 +0100 )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

Stats

Asked: 2020-02-25 13:40:19 +0100

Seen: 579 times

Last updated: Feb 26 '20