I am trying to write a recursive function which returns a copy of a list where neighbouring elements have been swapped. For example, swapElements([2, 3, 4, 9]) would return [3, 2, 9, 4].
This is my code as of now:
def swapElements(mylist):
if len(mylist) == 1:
pass
if len(mylist) == 2:
mylist[0], mylist[1] = mylist[1], mylist[0]
else:
mylist[0], mylist[1] = mylist[1], mylist[0]
swapElements(mylist[2:])
return mylist
When I run this function it only returns the list with the first two elements swapped, does anyone know why this function is not swapping any other elements other than the first two and how I could fix it?
In your question it says you wish to return a copy . Your function mutates mylist
in-place. Additionally, pass
has a return value of None
. You can simplify the function like so -
def swap (a = []):
if len(a) < 2:
return a
else:
return [ a[1], a[0] ] + swap(a[2:])
print(swap([2, 3, 4, 9]))
# [2, 3, 4, 9]
print(swap([2, 3, 4, 9, 6]))
# [2, 3, 4, 9, 6]
print(swap([1]))
# [1]
print(swap())
# []
I would let the recursion do the work and, if this is Python 3, do something less index-oriented like:
def swapPairs(array):
if len(array) < 2:
return array
a, b, *rest = array
return [b, a, *swapPairs(rest)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.