What will be the output of the following code?
import numpy as np
arr = np.array([1, 2, 3, 4])
result = arr * arr[::-1]
print(result)
[1, 4, 9, 16]
[4, 6, 6, 4]
[4, 6, 6]
[4, 4, 4, 4]
Step 1: Create the NumPy array
The line:
creates a 1D NumPy array:
Step 2: Reverse the array using arr[::-1]
The slicing operation arr[::-1] reverses the array:
Step 3: Element-wise multiplication
In NumPy, when you multiply two arrays of the same shape, the multiplication is element-wise. This means each element in one array is multiplied by the corresponding element in the other array.
Here:
Performing the element-wise multiplication:
Step 4: Print the result
Finally:
outputs:
Key Points:
- arr[::-1] reverses the array.
- Element-wise operations are default behavior in NumPy when performing arithmetic on arrays of the same size.
- The multiplication here computes each element as arr[i] * arr[len(arr)-i-1]
0 Comments:
Post a Comment