zach_93
zach_93

Reputation: 17

Recursion assignment

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)

The code above prints, but it prints the aList in order, from a-h. LIKE SO: "abcdefgh"

I need to print every two letters in reverse; LIKE SO: "badcfehg"

Upvotes: 0

Views: 325

Answers (3)

Mulan
Mulan

Reputation: 135367

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]

Upvotes: 0

meowgoesthedog
meowgoesthedog

Reputation: 15035

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

Upvotes: 2

Arya
Arya

Reputation: 1469

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."

Upvotes: 0

Related Questions