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 = [
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]
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
Whenever you have a recursion problem, you need to ask yourself two questions:
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."