Invert an Array
In this lesson, we will learn how to inverse an array recursively.
We'll cover the following...
What does “Invert an Array” mean?
Our task is to flip the elements of the array, meaning we will make the first element of the array the last element, the second element the second last element, and so on.
Inverting an array
Implementation
Press + to interact
def reverse(array):# Base case1if len(array) == 0: # If we encounter an empty array, simply return an empty arrayreturn []# Base case2elif len(array) == 1 : # Inverting an array of size 1 returns the same arrayreturn array# Recursive casereturn [array[len(array) - 1]] + reverse(array[:len(array) - 1])# The first part is storing the last element to be appended later# The second part is calling another instance of the same function with the last element removed# Driver Codearray = [1, 2, 3, 4]print(reverse(array))
Explanation
In the code snippet above, we break the last element of the array, which will be added to the front of the array.
In each function call, we continue breaking the last element and ...