27
[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 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
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)
Output:
[90, 5, 8, 89, 65, 2, 1, 12, 23, 10]
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
https://kdsingh4.blogspot.com/2021/10/recursive-how-to-reverse-array-or.html
27