>>> 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
只会返回该字符串。例如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”。在如果您想跟踪调用,请添加一些打印语句:
我没有在调试器中运行您的代码,所以我不能确切地看到堆栈跟踪,但这是因为您递归地调用了
f()
两次。这似乎是对字符串的过度操作导致意外的转换。如果要递归地反转字符串,下面的代码相当流行:样本结果:
^{pr2}$既然如此,我想这是一个学习练习?),一种更为python的方法来反转字符串是使用extended slice syntax
[being:end:step]
。在相关问题 更多 >
编程相关推荐