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
googlai
V2EX  ›  Python

Python 学习手册中递归求和代码的运行为什么打印每次递归的对象

  •  
  •   googlai · 2023-01-23 09:17:47 +08:00 · 1993 次点击
    这是一个创建于 430 天前的主题,其中的信息可能已经有所发展或是发生改变。

    下面是 jupyter 里的代码,除了第 1 个小例子要求每次递归调用都打印出对象外,其余函数都没有要求打印的代码逻辑呀,但是运行的结果是每次打印递归对象,除了最后一个间接递归,其他直接递归调用的结果我有点不理解,有没有懂得 V 友劳烦解个惑,先行谢过。

    def mysum(L):
        print(L)
        if not L:
            return 0
        else:
            return L[0] + mysum(L[1:])
        
    
    mysum([1, 2, 3, 4, 5])
    
    [1, 2, 3, 4, 5]
    [2, 3, 4, 5]
    [3, 4, 5]
    [4, 5]
    [5]
    []
    
    
    
    
    
    15
    
    def mysum1(L):
        return L[0] if len(L)==1 else L[0] + mysum(L[1:])
    
    mysum1([1, 2, 3, 4, 5])
    
    [2, 3, 4, 5]
    [3, 4, 5]
    [4, 5]
    [5]
    []
    
    
    
    
    
    15
    
    def mysum2(X):
        first, *rest = X
        return first if not rest else first + mysum(rest)
    
    mysum2([1, 2, 3, 4, 99])
    
    [2, 3, 4, 99]
    [3, 4, 99]
    [4, 99]
    [99]
    []
    
    
    
    
    
    109
    
    def mysum3(Y):
        if not Y: return 0
        return noempty(Y)
    
    def noempty(Y):
        return Y[0] + mysum3(Y[1:])
    
    mysum3([5, 2, 3, 4, 99])
    
    113
    
    3 条回复    2023-01-23 11:06:35 +08:00
    xiri
        1
    xiri  
       2023-01-23 09:22:25 +08:00 via Android   ❤️ 1
    你的 mysum1 和 mysum2 里面不是都调用了 mysum 嘛? mysum 里面有打印啊,,,
    googlai
        2
    googlai  
    OP
       2023-01-23 09:30:21 +08:00
    @xiri 原来是我自己书写错误,非常感谢指正。
    stephenyin
        3
    stephenyin  
       2023-01-23 11:06:35 +08:00
    @googlai #2 -_-||
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2955 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:13 · PVG 23:13 · LAX 08:13 · JFK 11:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.