Ajay
Ajay

Reputation: 156

Why is my function to Reverse an array not working?

Wrote a recursive function to reverse an array but its producing the same array. why?

def reverseArray(arr):
    l=0
    r=len(arr)-1
    if l<r:
        arr[l],arr[r] = arr[r], arr[l]
        reverseArray(arr[l+1:r])

if __name__ == "__main__":
    arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
    reverseArray(arr)
    print(arr)

Upvotes: 1

Views: 107

Answers (2)

Hadar
Hadar

Reputation: 668

if you're interested in a recursive approach you can use

def reverse_helper(A, start, end):
    if start >= end:
        return
    A[start], A[end] = A[end], A[start]
    reverse_helper(A, start+1, end-1)

def reverse(A):
    return reverse_helper(A,0,len(A)-1)

Or

def reverse(t):
  if not t:
    return []
  else
    return [ *reverse(t[1:]), t[0] ]

Upvotes: 0

Anh Nhat Tran
Anh Nhat Tran

Reputation: 562

arr[l+1:r] creates a copy of the original array. So your original array will be the same.

Upvotes: 1

Related Questions