简体   繁体   English

python 递归 function 从 0 打印到 n?

[英]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.我正在尝试编写一个从0打印到n的递归 function,但我不知道该怎么做。 I accidentally made one that prints from n to 0 though:我不小心做了一个从n0的打印:

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 ?我不知道这是否有帮助,也许我可以更改代码中的某些内容以使其 go 从0变为n

You're about 99% there. 那里你大约99%。

Think of your base case and your recursive step - when you hit 0, what do you want to do? 想想你的基本案例和你的递归步骤 - 当你达到0时,你想做什么? When you're still working your way down from n , what do you want to happen? 当你还在从自己的方式工作下来n ,你想要什么发生?

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. 当您将调用推送到堆栈时,如果不满足您的最终用例,您将继续添加更多调用,直到达到n == 0基本情况,然后您将专门开始打印值。

The other calls will then fall through to the print statement, as their execution has returned to the line after the conditional. 然后其他调用将进入print语句,因为它们的执行已经返回到条件后的行。

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)

You almost got it! 你几乎得到了它! here's a fixed, simplified version: 这是一个固定的简化版本:

def countup(n):
    if n >= 0:
        countup(n - 1)
        print(n)

Notice that: 请注意:

  • You don't have to return anything from a recursive function that only prints values 您不必从仅打印值的递归函数返回任何内容
  • For printing in ascending order, the print statement must be placed after the recursive call 要按升序print必须在递归调用之后放置print语句
  • The recursion exits when n < 0 , given that we're only printing, there's nothing left to be done afterwards and it's ok to return None (Python's default return value) n < 0时递归退出,假设我们只是打印,之后没有什么可以做的,可以返回None (Python的默认返回值)

UPDATE UPDATE

It seems that writing a tail recursive solution is all the rage around here :) oh well, here's my shot at it, a simplified and tail-recursive version of @AndyHayden's idea - using the tail call optimization decorator recipe : 似乎写一个尾递归解决方案在这里风靡一时:)哦,好吧,这是我的镜头,@ AndyHayden的想法的简化和尾递归版本 - 使用尾调用优化装饰器配方

@tail_call_optimized
def countup(N, n=0):
    print(n)
    if n < N:
        countup(N, n + 1)

Either way, it works as expected: 无论哪种方式,它都按预期工作:

countup(5)
=> 0
   1
   2
   3
   4
   5

You can replace the 0 and the n, and the + with a - to make your recursive countdown function to a recursive countup: 您可以将0和n替换为+,将+替换为 - 以使递归倒计时函数成为递归计数:

def countup(N, n=0):
    print(n)
    if n == N:
        return
    return countup(N, n + 1)

And call it as follows: 并将其称为如下:

countup(3)

@JFSebastian points out this algorithm has the benefit of being O(1) rather than O(n), as discussed in this excellent article about the difference between a linear and iterative recursion, if used with the @tail_call_optimized decorator. @JFSebastian指出这个算法的好处是O(1)而不是O(n),正如这篇关于线性和迭代递归之间差异的优秀文章所讨论的,如果与@tail_call_optimized装饰器一起使用的@tail_call_optimized

You can do this 你可以这样做

def fun(num,n):
    if num<n:
        print(num)
        fun(num+1,n)
n=int(input())
print(fun(0,n+1)) 

you can try this method as well:你也可以试试这个方法:

def recursion_print(n):
    if n==0:
      print(n)
    else:
      recursion_print(n-1)
      print(n)


recursion_print(9)

It should be best answer from my side.I hope u like this这应该是我这边的最佳答案。我希望你喜欢这个

 def countdown(n): 
    if n >0:    #this condition if n is greater than 0 untill run the program.
        countdown(n-1)   #this is recursion (calling itself).
    print(n)   #print the numbers.
countdown(10)   #function arguments.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM