递归内部递归和添加

时间:2015-09-16 21:42:34

标签: python recursion

我查了一下这个问题,但真的找不到答案。我只是无法绕过这个递归示例中的逻辑;

def f(s):
 if len(s) <= 1:
    return s
 return f(f(s[1:])) + s[0] #Note double recursion

我试图列出这些步骤,但我不知道我们是否确实先添加s [0]然后再将其传递给f(s)。有人能够一步一步地或以干净的方式解释这个吗?

谢谢,

1 个答案:

答案 0 :(得分:0)

我不知道有一种简洁的方式来描述这是做什么的。但是,我将其分解为可理解的部分并插入打印语句以进行彻底的跟踪。

def f(s):
    print "ENTER, s=", s
    if len(s) <= 1:
        return_val = s
        print "(1)  len <= 1; return", return_val
    else:
        print "(2a) len >  1; recur"
        first_call = f(s[1:])
        print "(2b) len >  1; first_call:", first_call
        return_val = f(first_call) + s[0]
        print "(2c) len >  1; return", return_val
    print "LEAVE ...", s
    return return_val

print f('abc')
print f('abcd')
print f('0123456789')

这是前两个字符串的输出;第三个是相当冗长的。

ENTER, s= abc
(2a) len >  1; recur
ENTER, s= bc
(2a) len >  1; recur
ENTER, s= c
(1)  len <= 1; return c
LEAVE ... c
(2b) len >  1; first_call: c
ENTER, s= c
(1)  len <= 1; return c
LEAVE ... c
(2c) len >  1; return cb
LEAVE ... bc
(2b) len >  1; first_call: cb
ENTER, s= cb
(2a) len >  1; recur
ENTER, s= b
(1)  len <= 1; return b
LEAVE ... b
(2b) len >  1; first_call: b
ENTER, s= b
(1)  len <= 1; return b
LEAVE ... b
(2c) len >  1; return bc
LEAVE ... cb
(2c) len >  1; return bca
LEAVE ... abc
bca
ENTER, s= abcd
(2a) len >  1; recur
ENTER, s= bcd
(2a) len >  1; recur
ENTER, s= cd
(2a) len >  1; recur
ENTER, s= d
(1)  len <= 1; return d
LEAVE ... d
(2b) len >  1; first_call: d
ENTER, s= d
(1)  len <= 1; return d
LEAVE ... d
(2c) len >  1; return dc
LEAVE ... cd
(2b) len >  1; first_call: dc
ENTER, s= dc
(2a) len >  1; recur
ENTER, s= c
(1)  len <= 1; return c
LEAVE ... c
(2b) len >  1; first_call: c
ENTER, s= c
(1)  len <= 1; return c
LEAVE ... c
(2c) len >  1; return cd
LEAVE ... dc
(2c) len >  1; return cdb
LEAVE ... bcd
(2b) len >  1; first_call: cdb
ENTER, s= cdb
(2a) len >  1; recur
ENTER, s= db
(2a) len >  1; recur
ENTER, s= b
(1)  len <= 1; return b
LEAVE ... b
(2b) len >  1; first_call: b
ENTER, s= b
(1)  len <= 1; return b
LEAVE ... b
(2c) len >  1; return bd
LEAVE ... db
(2b) len >  1; first_call: bd
ENTER, s= bd
(2a) len >  1; recur
ENTER, s= d
(1)  len <= 1; return d
LEAVE ... d
(2b) len >  1; first_call: d
ENTER, s= d
(1)  len <= 1; return d
LEAVE ... d
(2c) len >  1; return db
LEAVE ... bd
(2c) len >  1; return dbc
LEAVE ... cdb
(2c) len >  1; return dbca
LEAVE ... abcd
dbca