Python中doublerecursion的结果

2024-09-26 22:09:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于这些代码行的问题。我想弄清楚打印声明会显示什么:

def f(s):
    if len(s) <= 1:
        return s
    return f(f(s[1:])) + s[0]
print f("abcd")

我原以为它会打印:dcba,但结果却是:dbca。在

如果有人能向我解释为什么会发生这种事,我会非常感激。我的目标不是以打印dcba的方式更改代码,而是理解它为什么会这样。提前感谢你提供的每一个帮助。 干杯


Tags: 代码声明目标lenreturnifdef方式
3条回答

我们从头开始吧。在

对一个单字符字符串调用f只会返回该字符串。例如f(“a”)返回“a”。在

对两个字符的字符串调用f将返回反转的字符串。例如f(“ab”)==f(f(“b”))+“a”==f(“b”)+“a”==“b”+“a”==“ba”。在

对三个字符的字符串调用f将返回最左边的字符移到右边的字符串。例如f(“abc”)==f(f(“bc”))+“a”==f(“cb”)+“a”==“bc”+“a”==“bca”。在

对一个四个字符的字符串调用f会返回一些与您得到的结果相对应的复杂结果:f(“abcd”)==f(f(“bcd”))+“a”==f(“cdb”)+“a”==“dbc”+“a”==“dbca”。在

如果您想跟踪调用,请添加一些打印语句:

>>> def f(s):
...     print
...     print "recieved", s
...     if len(s) <= 1:
...         print "returning", s
...         return s
...     print "returning f(f(%s)) + %s" % (s[1:], s[0])
...     return f(f(s[1:])) + s[0]
...
>>> print f("abcd")

recieved abcd
returning f(f(bcd)) + a

recieved bcd
returning f(f(cd)) + b

recieved cd
returning f(f(d)) + c

recieved d
returning d

recieved d
returning d

recieved dc
returning f(f(c)) + d

recieved c
returning c

recieved c
returning c

recieved cdb
returning f(f(db)) + c

recieved db
returning f(f(b)) + d

recieved b
returning b

recieved b
returning b

recieved bd
returning f(f(d)) + b

recieved d
returning d

recieved d
returning d
dbca

我没有在调试器中运行您的代码,所以我不能确切地看到堆栈跟踪,但这是因为您递归地调用了f()两次。这似乎是对字符串的过度操作导致意外的转换。如果要递归地反转字符串,下面的代码相当流行:

def f(s):
    if len(s) == 0:
        return s
    return f(s[1:]) + s[0]

样本结果:

^{pr2}$

既然如此,我想这是一个学习练习?),一种更为python的方法来反转字符串是使用extended slice syntax[being:end:step]。在

print 'abcd'[::-1]
>>> dcba

相关问题 更多 >

    热门问题