Recursion assignment

后端 未结 3 1689
时光说笑
时光说笑 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:30

    Here's a pretty simple way

    def swap (l):
      if len (l) < 2:
        return list (l)
      else:
        return [ l[1], l[0] ] + swap (l[2:])
    
    print (swap ("abcdefgh"))
    # ['b', 'a', 'd', 'c', 'f', 'e', 'h', 'g']
    

    It works on arrays too

    print (swap ([1, 2, 3, 4, 5, 6, 7]))
    # [2, 1, 4, 3, 6, 5, 7]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-26 16:42

    Whenever you have a recursion problem, you need to ask yourself two questions:

    1. What is the base case (the simplest possible case). There can be more than one.
    2. If I'm not in the base case, how can I write some code that calls the current function in a case closer to the base case.

    In your case, the base case seems to be correct, but what you're returning doesn't seem to be correct for len==0. If a string is length zero, what would you be returning?

    Your second base case looks fine, but you shouldn't mix printing and returning. Just return the aList[0], and then you can print out the output from calling your swap function.

    For your recursive case, think about just the string "ab" - how do you get the recursive call to return "ba."

    0 讨论(0)
提交回复
热议问题