从0打印到n的python递归函数? [英] python recursive function that prints from 0 to n?

查看:27
本文介绍了从0打印到n的python递归函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个从 0 打印到 n 的递归函数,但我不知道该怎么做.我不小心做了一个从 n 打印到 0 的代码:

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)

我不知道这是否有帮助,也许我可以更改代码中的某些内容,使其从 0 变为 n?

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?

推荐答案

你几乎明白了!这是一个固定的简化版本:

You almost got it! here's a fixed, simplified version:

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

请注意:

  • 您不必从仅打印值的递归函数中返回任何内容
  • 要按升序打印,print 语句必须放在递归调用之后
  • n <时递归退出0,鉴于我们只是在打印,后面就没什么可做的了,返回None(Python默认返回值)
  • 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
  • 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)

更新

编写尾递归解决方案似乎在这里风靡一时:) 哦,这是我的尝试,@AndyHayden 想法的简化尾递归版本 - 使用尾调用优化装饰器 配方:

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:

@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

这篇关于从0打印到n的python递归函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆