1

After viewing code samples from RosettaCode and Literate Programming I am still confused at how to implement memoization for a problem I am doing.

In the problem, I perform a magic() formula, similar to a Collatz Sequence on the number, and eventually the sequence either yields 1,2,or 3.

for example it might go:

123849 -> 2342453 -> 1233453 ->3

I would like to store the values after I calculate them, so that as I perform magic() on increasingly big numbers, the run time is reduced. So for instance, after doing magic(123849), I would like to store 123849, 2342453, and 1233453. If any of these numbers comes up in the future, instead of having to perform the magic function, it will immediately output 3.

ones=[]
twos=[] 
threes=[]
def magic(x):
    # Memoization
    if ones.count(x)>0: return 1
    if twos.count(x)>0: return 2
    if threes.count(x)>0: return 3 
    sequence=[]
    <generate magic sequence, add each value to sequence>
    # Add each sequence to the appropriate list
    if final_value==1: ones.extend(sequence)
    if final_value==2: twos.extend(sequence)
    if final_value==3: threes.extend(sequence)
    return final_value

My question: is there a better (more efficient/faster) way of implementing this memoization? Can I use lists instead of dicts?

1 Answer 1

1

Definitely check out functools.lru_cache, the Python stdlib's memoization implementation: http://docs.python.org/dev/library/functools.html#functools.lru_cach

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.