0

I've coded a function that finds all changes of n using the given coins when order makes a change.

def find_change(n, coins):
    if n < 0:
        return []

    if n == 0:
        return [[]]

    all_changes = []

    for last_used_coin in coins:
        curr_changes = find_change(n - last_used_coin, coins)

        for change in curr_changes:
            change.append(last_used_coin)

        all_changes.extend(curr_changes)

    return all_changes

print find_change(4, [1,2,3])

The code above is "normal" and now I want to code it again but as a memo. The values that will be saved in the memo are mutable therefore I should use deepcopy but I don't know how to use it. Can someone show me how?

EDIT: idea how to use deepcopy:

from copy import deepcopy
lst1 =[[1], [2]]
lst 2 = deepcopy(lst1)
print lst

and we get:

[[1], [2], [3]]
3
  • Your code does not execute, please post a working version of this function. For starters, find_changes is a typo, but the function does not complete execution. Please also post a working example of using the function. Commented Jan 20, 2014 at 1:41
  • Thanks for the example, but the code still does not execute Commented Jan 20, 2014 at 1:54
  • @PeterGibson - sorry, what about now? Commented Jan 20, 2014 at 2:02

1 Answer 1

2

Your only changing argument is n, so just use it as the key for your lookup table:

if n not in cache:
    ...

You could even turn it into a decorator:

def memoized(function):
    cache = {}

    def inner(n, coins):
        if n not in cache:
            cache[n] = function(n, coins)

        return cache[n]

    return inner

@memoized
def find_change(n, coins):
    ...
Sign up to request clarification or add additional context in comments.

18 Comments

First of all, thank you very much. But, I would really want to use deepcopy, I tried to undertstand how it works and how to make this code in memo but I had no success. I would really like if you could try to do this way. Thanks again.
@user3210483: Using deepcopy won't make your list immutable. Your list doesn't change in the first place, so why use it as the key for a lookup table? The only thing that changes is n.
I have an idea how to try to use deepcopy, please look at my edit in the first message. thanks.
@user3210483: Change cache[n] = function(n, coins) to cache[n] = deepcopy(function(n, coins)) and I guess
Perhaps coins is supposed to change? This would make sense given the desire to use deepcopy. @user3210483 Are you selecting change from a limited set of coins?
|

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.