Recursion assignment

后端 未结 3 1804
时光说笑
时光说笑 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: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."

提交回复
热议问题