DEV Community

Cover image for [Python] How to Reverse array using recursive function
Kuldeep Singh
Kuldeep Singh

Posted on

[Python] How to Reverse array using recursive function

In this article we are going to cover up how we can reverse an array or string using recursive function.

Before Writing any code let's explore about what recursive method is:

What is Recursion?
Recursion is a process in which a function calls itself as a subroutine. This allows the function to be repeated several times, since it calls itself during its execution. Functions that incorporate recursion are called recursive functions.

Recursion is often seen as an efficient method of programming since it requires the least amount of code to perform the necessary functions. However, recursion must be incorporated carefully, since it can lead to an infinite loop if no condition is met that will terminate the function.

So now you guys have idea about what recursion is.

How will be the flow of the code will going to be means algorithm

  1. we are going to use depth way to get the each value of array from ending to beginning.
  2. Handling the indexes to don't get bounce error from it(index not exists kind) via adding if condition
  3. directly appending each index to a array variable.
  4. Begin process again from 1 means calling function to iterate until 2 step not get it wants.

Code:



arr = [10, 23, 12, 1, 2, 65, 89, 8, 5, 90]
def recursion(arr,depth):
  str = [] # step 1
  if depth == -1: #step 2
    return str

  str.append(arr[depth]) #step 3
  n = recursion(arr,depth-1) #step 4 
  if len(n) > 0:
    str.extend(n)

  return str

r = recursion(arr,len(arr)-1)
print(r)


Enter fullscreen mode Exit fullscreen mode

Output:



[90, 5, 8, 89, 65, 2, 1, 12, 23, 10]


Enter fullscreen mode Exit fullscreen mode

You can checkout this to know how to reverse array also in golang and javascript
https://kdsingh4.blogspot.com/2021/10/recursive-how-to-reverse-array-or.html

Top comments (0)