Rotating a 4x4 array 90 degrees Counterclockwise using NumPy
Write a NumPy program to create a 4x4 array with random values and rotate the array 90 degrees counterclockwise.
Sample Solution:
Python Code:
import numpy as np
# Create a 4x4 array with random values
array = np.random.random((4, 4))
# Print the original array
print("Original Array:\n", array)
# Rotate the array 90 degrees counterclockwise
rotated_array = np.rot90(array)
# Print the rotated array
print("Array after 90 degrees counterclockwise rotation:\n", rotated_array)
Output:
Original Array: [[0.16774949 0.30263452 0.75987069 0.368299 ] [0.39865392 0.4344374 0.29780849 0.07469577] [0.94042863 0.37602418 0.36429796 0.76098639] [0.43534721 0.52836575 0.65394788 0.47563204]] Array after 90 degrees counterclockwise rotation: [[0.368299 0.07469577 0.76098639 0.47563204] [0.75987069 0.29780849 0.36429796 0.65394788] [0.30263452 0.4344374 0.37602418 0.52836575] [0.16774949 0.39865392 0.94042863 0.43534721]]
Explanation:
- Import NumPy: Import the NumPy library to work with arrays.
- Create a Random 4x4 Array: Generate a 4x4 array filled with random values using np.random.random.
- Print the Original Array: Print the original 4x4 array for reference.
- Rotate the Array: Use np.rot90 to rotate the array 90 degrees counterclockwise.
- Print the Rotated Array: Print the array after rotating it 90 degrees counterclockwise.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics