Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 views
in Technique[技术] by (71.8m points)

recursion - python recursive function that prints from 0 to n?

I am trying to write a recursive function that prints from 0 to n, but I have no idea how to do it. I accidentally made one that prints from n to 0 though:

def countdown(n):
    print(n)
    if n == 0:
        return 0
    return countdown(n - 1)

I don't know if that helps or not, maybe I can change something in the code to make it go from 0 to n?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're about 99% there.

Think of your base case and your recursive step - when you hit 0, what do you want to do? When you're still working your way down from n, what do you want to happen?

If you reverse the order in which you print the value, you'll reach your desired result.

def countdown(n):
    if n != 0:
        countdown(n-1)
    print(n)

The reason this works is that recursive calls go on the call stack. As you push calls onto the stack, while your end case isn't met, you'll keep adding more calls until you reach your base case of n == 0, and then you'll exclusively start printing the values.

The other calls will then fall through to the print statement, as their execution has returned to the line after the conditional.

So, the call stack looks something like this:

countdown(5)
    countdown(4)
        countdown(3)
            countdown(2)
                countdown(1)
                    countdown(0)
                    print(0)
                print(1)
            print(2)
         print(3)
     print(4)
print(5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...