0

So I am doing minimum coin change problem recursively in python. I wanted to visualize how many recursive calls it's making. So I put a "print 'recursion'" in my function. But now it's continuously print recursion and not reaching output and program is not even stopping. Here is the program.

def min_coins(coins, change):
    print 'recursion' #program works without this line
    mincoins = change
    if change in coins:
        return 1
    else:
        for i in coins:
            if i<=change:
                numcoins = 1 + min_coins(coins, change-i)
                if(numcoins < mincoins):
                    mincoins = numcoins
    return mincoins

c = [1,5,25]
d = 50

print min_coins(c, d)
7
  • 3
    Works for me, can't reproduce. And this should be the case - the print can't affect that code. Perhaps you are not waiting long enough to see the final output, or it is being lost in a sea of "recusion" lines? Commented Feb 1, 2016 at 10:40
  • 1
    thanks. It turns out I wasn't waiting long enough. Commented Feb 1, 2016 at 10:52
  • 1
    If you think about the problem you are trying to solve you should be able to come up with a much better solution that only needs a fraction of the recursive calls. Commented Feb 1, 2016 at 10:54
  • @Duncan Yes now I am working on dynamic program. But wanted to make a recursive program first. But even this recursive program is incorrent as for coins = [5,25] change = 56 it is showing 4 coins. Commented Feb 1, 2016 at 11:01
  • Recursive is fine (my first attempt is 2395 recursive calls for your original problem). Hint: remember all the results you've calculated so far and then a new value is either a single coin or the minimum of all the ways of combining two smaller amounts. Commented Feb 1, 2016 at 11:06

1 Answer 1

6

Consoles are quite slow, and you weren't patient enough:

python your_program.py | wc -l
684886

There are better ways, use a global counter variable or return a pair of (mincoins, counter).

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

4 Comments

Okay thanks for clarifying. But when I ran the code without print statement the output came in less than 2 seconds. But when I added print it's running for much more time. Why is it so?
@ailhahc because Python can do 684886 recursive calls in under 2 seconds but not when it has to write the output to the console as well. print is slow!
It might be worth printing a dynamic variable when debugging, perhaps printing coins and change at each recursion to see the state of your program.
@Duncan: nope. On my computer, print only doubles the execution time (when output is redirected). As I said, consoles are notoriously slow.

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.