Recursion assignment

后端 未结 3 1690
时光说笑
时光说笑 2021-01-26 16:02
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 = [         


        
3条回答
  •  心在旅途
    2021-01-26 16:34

    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
    

提交回复
热议问题