V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
mintLeaf
V2EX  ›  Python

这个递归的返回值为什么是 0,1(代码格式已修改)

  •  
  •   mintLeaf · 2016-06-08 19:05:48 +08:00 · 2683 次点击
    这是一个创建于 2869 天前的主题,其中的信息可能已经有所发展或是发生改变。

    def a(i):
      if i==0:
        return
       i = i - 1
      a(i)
      print i

    a(2)

    5 条回复    2016-06-08 22:36:04 +08:00
    wjfz
        1
    wjfz  
       2016-06-08 19:07:45 +08:00
    你以为是 1 , 0 ?
    mornlight
        2
    mornlight  
       2016-06-08 19:11:14 +08:00   ❤️ 1
    你的疑惑在哪呢?
    里面
    a(i)
    print i
    这两句,要先等 a(i)执行完才会 print ,最底层的递归调用先 print 结果,最底层的调用是 a(0),没有输出,再往上一层是 a(1),输出 0 ,再往上是 a(2),输出 1
    SuperFashi
        3
    SuperFashi  
       2016-06-08 19:12:33 +08:00 via Android   ❤️ 1
    你高中的程序框图是不是没认真学啊……
    进入 a(i=2)
    判断==(否)
    i=1
    进入 a(i=1)
    {
    判断==(否)
    i=0
    进入 a(i=0)
    {
    判断==(是)
    返回
    }
    打印 i (也就是 0)
    返回
    }
    打印 i (也就是 1)
    返回
    mintLeaf
        4
    mintLeaf  
    OP
       2016-06-08 19:22:17 +08:00
    多谢大家,明白了
    iamxi
        5
    iamxi  
       2016-06-08 22:36:04 +08:00
    print i 这句在 a(i)之后,所以优先执行 a(i)内的 print i 。
    而且 print i 这句在 a(i)之后,不算尾递归。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3269 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 13:47 · PVG 21:47 · LAX 06:47 · JFK 09:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.