本文介绍了递归分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def swap(aList):
if len(aList) == 0:
return 0
elif len(aList) == 1:
print(aList[0])
return aList[0]
return aList[0] + swap(aList[2:])
aList = [["abcdefgh"]]
swap(aList)
上面的代码可以打印,但是会按顺序从a-h打印aList.像这样:"abcdefgh"
The code above prints, but it prints the aList in order, from a-h. LIKE SO:"abcdefgh"
我需要每两个字母反向打印一次;像这样:"badcfehg"
I need to print every two letters in reverse; LIKE SO:"badcfehg"
推荐答案
为什么使用2D数组?您只是交换其成员(一维数组),而不是交换字符串中的字符.只需传递字符串本身-索引运算符就可以访问每个字符.另外,请记住,+
运算符对于字符串是非可交换的:
Why use a 2D array? You are just swapping its members (1D arrays) rather than the characters in your string. Just pass in the string itself - the indexing operator can access each character. Also, remember that the +
operator is non-commutative for strings:
def swap(s):
if len(s) == 0:
return ""
elif len(s) == 1:
return s
return s[1] + s[0] + swap(s[2:])
print(swap("abcdefgh")) # --> badcfehg
这篇关于递归分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!