Numpy - Reverse elements of large array using For loop and Optimization
NumPy: Performance Optimization Exercise-20 with Solution
Write a NumPy program that creates a large NumPy array and write a function to reverse its elements using a for loop. Optimize it using NumPy's slicing operations.
Sample Solution:
Python Code:
import numpy as np
# Generate a large 1D NumPy array with random integers
large_array = np.random.randint(1, 1000000, size=1000000)
# Function to reverse the array using a for loop
def reverse_with_loop(arr):
reversed_array = np.empty_like(arr)
for i in range(len(arr)):
reversed_array[i] = arr[len(arr) - 1 - i]
return reversed_array
# Reverse the array using the for loop method
reversed_with_loop = reverse_with_loop(large_array)
# Reverse the array using NumPy's slicing operations
reversed_with_numpy = large_array[::-1]
# Display first 10 elements of the reversed arrays to verify
print("First 10 elements of the array reversed using for loop:")
print(reversed_with_loop[:10])
print("First 10 elements of the array reversed using NumPy slicing:")
print(reversed_with_numpy[:10])
Output:
First 10 elements of the array reversed using for loop: [283195 306928 188280 377498 738210 923196 756211 836406 578638 560676] First 10 elements of the array reversed using NumPy slicing: [283195 306928 188280 377498 738210 923196 756211 836406 578638 560676]
Explanation:
- Importing numpy: We first import the numpy library for array manipulations.
- Generating a large array: A large 1D NumPy array with random integers is generated.
- Defining the function: A function reverse_with_loop is defined to reverse the array using a for loop.
- Reversing with loop: The array is reversed using the for loop method.
- Reversing with numpy: The array is reversed using NumPy's slicing operations.
- Displaying results: The first 10 elements of the reversed arrays from both methods are printed out to verify correctness.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Numpy - Calculate Matrix product of two large arrays using For loops and Optimization.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/numpy-reverse-elements-of-large-array-using-for-loop-and-optimization.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics